Golang remote transfer of files

Source: Internet
Author: User
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([]ssh.AuthMethod, 0)  auth = append(auth, ssh.Password(password))  clientConfig = &ssh.ClientConfig{    User:    user,    Auth:    auth,    Timeout: 30 * time.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 {    return nil, err  }  return sftpClient, nil}

Send file

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

package mainimport (  "fmt"  "log"  "os"  "path"  "time"  "github.com/pkg/sftp"  "golang.org/x/crypto/ssh")func main() {  var (    err        error    sftpClient *sftp.Client  )  // 这里换成实际的 SSH 连接的 用户名,密码,主机名或IP,SSH端口  sftpClient, err = connect("root", "rootpass", "127.0.0.1", 22)  if err != nil {    log.Fatal(err)  }  defer sftpClient.Close()  // 用来测试的本地文件路径 和 远程机器上的文件夹  var localFilePath = "/path/to/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, 1024)  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 mainimport (  "fmt"  "log"  "os"  "path"  "time"  "github.com/pkg/sftp"  "golang.org/x/crypto/ssh")func main() {  var (    err        error    sftpClient *sftp.Client  )  // 这里换成实际的 SSH 连接的 用户名,密码,主机名或IP,SSH端口  sftpClient, err = connect("root", "rootpass", "127.0.0.1", 22)  if err != nil {    log.Fatal(err)  }  defer sftpClient.Close()  // 用来测试的远程文件路径 和 本地文件夹  var remoteFilePath = "/path/to/remote/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/

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.