golang 遠端傳輸檔案

2021-07-25 10:52:13 字數 2256 閱讀 9244

之前有一篇介紹如何使用 golang 通過ssh協議來執行遠端命令:golang 執行遠端命令 同樣,通過ssh協議也可以使用 golang 來遠端傳輸檔案。

除了 ssh 的庫,為了傳輸檔案,還需要用到 github.com/pkg/sftp 這個庫。

實現方式

由於是基於 ssh 協議實現的遠端檔案傳輸,所以先建立 ssh 的連線,再建立傳輸檔案的 sftp 客戶端。

func connect(user, password, host string, port int) (*sftp.client, error) 

// connet to ssh

addr = fmt.sprintf("%s:%d", host, port)

if sshclient, err = ssh.dial("tcp", addr, clientconfig); err != nil

// create sftp client

if sftpclient, err = sftp.newclient(sshclient); err != nil

return sftpclient, nil

}

傳送檔案

使用上面的 connect 方法建立 sftpclient 後,傳送檔案很簡單。

// 用來測試的本地檔案路徑 和 遠端機器上的資料夾

var localfilepath = "/path/to/local/file/test.txt"

var remotedir = "/remote/dir/"

srcfile, err := os.open(localfilepath)

if err != nil

defer srcfile.close()

var remotefilename = path.base(localfilepath)

dstfile, err := sftpclient.create(path.join(remotedir, remotefilename))

if err != nil

defer dstfile.close()

buf := make(byte,1024)

for

dstfile.write(buf)

} fmt.println("copy file to remote server finished!")

}獲取檔案

從遠端機器上獲取檔案的方式略有不同,但也很簡單。

// 用來測試的遠端檔案路徑 和 本地資料夾

var remotefilepath = "/path/to/remote/path/test.txt"

var localdir = "/local/dir"

srcfile, err := sftpclient.open(remotefilepath)

if err != nil

defer srcfile.close()

var localfilename = path.base(remotefilepath)

dstfile, err := os.create(path.join(localdir, localfilename))

if err != nil

defer dstfile.close()

if _, err = srcfile.writeto(dstfile); err != nil

fmt.println("copy file from remote server finished!")

}

golang 檔案壓縮 http 檔案傳輸

1.golang檔案傳輸 對檔案進行壓縮,同時考慮了linux 和 wins 目錄差異 func main 打包成zip檔案 func zip src dir string,zip file name string header,zip.fileinfoheader info path string...

FTP遠端傳輸檔案操作

1.與遠端建立連線 ftp ftp open serverip 使用username password登入後即可進行ftp操作。2.目錄操作 ls cd mkdir delete 刪除乙個檔案 mdelete 刪除一批檔案 檔名稱羅列 lcd 跳轉本機目錄 3.檔案傳輸 1 從遠端到本地 ftp g...

MAC上遠端傳輸檔案

2 上傳本地檔案到伺服器 scp path filename username servername path 例如scp users mac desktop test.txt root 123.207.170.40 root 例如 scp r root 192.168.0.101 root use...