您的位置 首页 golang

Golang 服务器间文件传输

类似shell,python等其他语言都可以通过 SSH 协议实现远程服务器命令调用,文件传输;Go也不例外,也有同样的实现方式。示例中通过引入ssh库和sftp库来实现,实现原理很简单就是socket tcp的实现封装。废话不多说,直接示例:

发送文件

使用上面的 connect 方法创建 sftpClient 后,发送文件很简单。

package main

import (

“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!”)

}

获取文件

从远程机器上获取文件的方式略有不同,但也很简单。

package main

import (

“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!”)

}

更多内容请关注每日编程,每天进步一点。

文章来源:智云一二三科技

文章标题:Golang 服务器间文件传输

文章地址:https://www.zhihuclub.com/86696.shtml

关于作者: 智云科技

热门文章

网站地图