Welcome 微信登录

首页 / 操作系统 / Linux / Golang 远程传输文件

概述

之前有一篇介绍如何使用 golang 通过SSH协议来执行远程命令:Golang 执行远程命令 同样,通过SSH协议也可以使用 golang 来远程传输文件。除了 SSH 的库,为了传输文件,还需要用到 github.com/pkg/sftp 这个库。

实现方式

废话不多说,直接看代码。 由于是基于 SSH 协议实现的远程文件传输,所以先创建 SSH 的连接,再创建传输文件的 sftp 客户端。func connect(user, password, host string, port int) (*sftp.Client, error) {var (auth []ssh.AuthMethodaddr stringclientConfig *ssh.ClientConfigsshClient*ssh.ClientsftpClient *sftp.Clienterrerror)// get auth methodauth = make([]ssh.AuthMethod, 0)auth = append(auth, ssh.Password(password))clientConfig = &ssh.ClientConfig{User:user,Auth:auth,Timeout: 30 * time.Second,}// connet to sshaddr = fmt.Sprintf("%s:%d", host, port)if sshClient, err = ssh.Dial("tcp", addr, clientConfig); err != nil {return nil, err}// create sftp clientif sftpClient, err = sftp.NewClient(sshClient); err != nil {return nil, err}return sftpClient, nil}

发送文件

使用上面的 connect 方法创建 sftpClient 后,发送文件很简单。package mainimport ("fmt""log""os""path""time""github.com/pkg/sftp""golang.org/x/crypto/ssh")func main() {var (errerrorsftpClient *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!")}

获取文件

从远程机器上获取文件的方式略有不同,但也很简单。package mainimport ("fmt""log""os""path""time""github.com/pkg/sftp""golang.org/x/crypto/ssh")func main() {var (errerrorsftpClient *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!")}

总结

上面的例子只是演示了文件传输,传输文件夹也很简单,只是多了遍历文件夹和创建文件夹的步骤,具体的函数可以自行查看 sftp 库中doc。本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-10/136204.htm