github.com/justinjmoses/evergreen@v0.0.0-20170530173719-1d50e381ff0d/remote/sftp.go (about)

     1  package remote
     2  
     3  import (
     4  	"github.com/pkg/errors"
     5  	"github.com/pkg/sftp"
     6  	"golang.org/x/crypto/ssh"
     7  )
     8  
     9  // SFTPGateway wraps an SFTP client.
    10  type SFTPGateway struct {
    11  
    12  	// the sftp client that the gateway is managing
    13  	Client *sftp.Client
    14  
    15  	// the remote host
    16  	Host string
    17  	// the user we'll access the file as on the remote machine
    18  	User string
    19  
    20  	// the file containing the private key we'll use to connect
    21  	Keyfile string
    22  }
    23  
    24  // Connect to the other side, and initialize the SFTP client.
    25  func (gateway *SFTPGateway) Init() error {
    26  
    27  	// configure appropriately
    28  	clientConfig, err := createClientConfig(gateway.User, gateway.Keyfile)
    29  	if err != nil {
    30  		return errors.Wrap(err, "error configuring ssh")
    31  	}
    32  
    33  	// connect to the other side
    34  	conn, err := ssh.Dial("tcp", gateway.Host, clientConfig)
    35  	if err != nil {
    36  		return errors.Wrapf(err, "error connecting to ssh server at `%v`", gateway.Host)
    37  	}
    38  
    39  	// create the sftp client
    40  	gateway.Client, err = sftp.NewClient(conn)
    41  	if err != nil {
    42  		return errors.Wrapf(err, "error creating sftp client to `%v`", gateway.Host)
    43  	}
    44  
    45  	return nil
    46  
    47  }
    48  
    49  // Close frees any necessary resources.
    50  func (gateway *SFTPGateway) Close() error {
    51  	return errors.WithStack(gateway.Client.Close())
    52  }