Golang remote transfer of files

Source: Internet
Author: User
Tags ssh port
This is a creation in Article, where the information may have evolved or changed.
                                                                                                     

Overview

One previous article describes how to use Golang to execute remote commands via the SSH protocol: Golang execute remote command Similarly, the SSH protocol can also use Golang to remotely transfer files.

In addition to the SSH library, in order to transfer files, you also need to use the GITHUB.COM/PKG/SFTP library.

Implementation method

Don't say much nonsense, just look at the code. Because it is a remote file transfer based on the SSH protocol, the SSH connection is created, and the SFTP client that transmits the file is created.

Func Connect (user, password, host string, Port int) (*SFTP. Client, error) { var (   auth         []SSH. Authmethod    ADDR         string    clientconfig *ssh. ClientConfig    sshclient    *SSH. Client    sftpclient   *sftp. Client    err          error  )  //Get auth method  auth = make ([]s Sh. Authmethod, 0)  auth = append (auth, ssh. Password (Password))  clientconfig = &ssh. clientconfig{   user:    user,    auth:    auth,    timeout:30 * ti Me. Second,  }  //connet to ssh  addr = fmt. Sprintf ("%s:%d", host, Port)  if sshclient, err = ssh. Dial ("TCP", addr, ClientConfig); Err! = Nil {   return nil, err  }  //create SFTP client  if sftpclient, err = sftp. Newclient (sshclient); Err! = Nil {  &Nbsp;return Nil, err  }  return sftpclient, nil} 

Send file

After creating sftpclient using the Connect method above, it is easy to send the file.

Package main import (  "FMT"   "Log"   "OS"   "path"   "Time"   "Github.com/pkg/sftp" & nbsp; " Golang.org/x/crypto/ssh ") Func main () { var (   err        error    SF Tpclient *sftp. Client  )  //here for the actual SSH connection username, password, hostname or IP,SSH port  sftpclient, err = connect ("root", "Rootpass", "127.0 .0.1 ","  if err! = Nil {   log. Fatal (Err)  }  defer sftpclient.close ()  //used to test the local file path and folder on the remote machine  var Localfilepath = "/path/t O/local/file/test.txt " var remotedir ="/remote/dir/" srcfile, err: = OS. Open (Localfilepath)  if err! = Nil {   log. Fatal (Err)  }  defer srcfile.close ()  var remotefilename = path. Base (Localfilepath)  dstfile, err: = Sftpclient.create (path. Join (Remotedir, remotefilename))  if err! = Nil {   log. Fatal (Err)  }  defer dstfile.close ()  buf: = Make([]byte, 1024x768)  for {   n, _: = Srcfile.read (buf)    if n = = 0 {     break    }    dstfile.write (BUF)  }  fmt. Println ("Copy file to remote server finished!")}

Get file

Getting files from a remote machine is slightly different, but it's also simple.

Package main import (  "FMT"   "Log"   "OS"   "path"   "Time"   "Github.com/pkg/sftp" & nbsp; " Golang.org/x/crypto/ssh ") Func main () { var (   err        error    s FtpClient *sftp. Client  )  //here for the actual SSH connection username, password, hostname or IP,SSH port  sftpclient, err = connect ("root", "Rootpass", "127.0 .0.1 ","  if err! = Nil {   log. Fatal (Err)  }  defer sftpclient.close ()  //used to test the remote file path and local folder  var Remotefilepath = "/path/to/r Emote/path/test.txt " var localdir ="/local/dir " srcfile, err: = Sftpclient.open (Remotefilepath)  if Err! = Nil {   log. Fatal (Err)  }  defer srcfile.close ()  var localfilename = path. Base (Remotefilepath)  dstfile, err: = OS. Create (path. Join (Localdir, LocalFilename))  if err! = Nil {   log. Fatal (Err)  }  defer Dstfile.close ()  if _, err = srcFile.writeto (Dstfile); Err! = Nil {   log. Fatal (Err)  }  fmt. Println ("Copy file from remote server finished!")}

Summarize

The above example just shows the file transfer, the transfer folder is also very simple, just a lot of steps to traverse the folder and create folders, the specific function can view the SFTP Library of Doc.

Source: http://blog.iotalabs.io/

This article from: Blog Park

Thanks to the author: wang_yb

View Original: Golang Remote transfer file




View Original: http://www.zoues.com/2016/10/20/golang-%e8%bf%9c%e7%a8%8b%e4%bc%a0%e8%be%93%e6%96%87%e4%bb%b6/
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.