Golang 使用 net 包通过 SFTP 发送文件到指定目录
以下是一个使用 Golang 中的 net 包通过 SFTP 发送文件到指定目录的示例代码:
package main
import (
"fmt"
"io/ioutil"
"os"
"golang.org/x/crypto/ssh"
"github.com/pkg/sftp"
)
func main() {
// 连接SSH服务器
sshClient, err := ssh.Dial("tcp", "example.com:22", &ssh.ClientConfig{
User: "user",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
})
if err != nil {
panic(err)
}
defer sshClient.Close()
// 创建SFTP客户端
sftpClient, err := sftp.NewClient(sshClient)
if err != nil {
panic(err)
}
defer sftpClient.Close()
// 打开本地文件
localFile, err := os.Open("example.txt")
if err != nil {
panic(err)
}
defer localFile.Close()
// 读取本地文件内容
fileBytes, err := ioutil.ReadAll(localFile)
if err != nil {
panic(err)
}
// 创建远程文件
remoteFile, err := sftpClient.Create("/path/to/remote/file/example.txt")
if err != nil {
panic(err)
}
defer remoteFile.Close()
// 将本地文件内容写入远程文件
_, err = remoteFile.Write(fileBytes)
if err != nil {
panic(err)
}
fmt.Println("文件发送成功")
}
在上面的代码中,我们首先通过 ssh.Dial() 方法连接 SSH 服务器,然后使用 sftp.NewClient() 方法创建 SFTP 客户端。接着,我们打开本地文件并读取其内容,然后使用 sftpClient.Create() 方法创建远程文件。最后,我们使用 remoteFile.Write() 方法将本地文件内容写入远程文件。
注意,上面的示例代码中使用了 'golang.org/x/crypto/ssh' 和 'github.com/pkg/sftp' 两个第三方库,需要先使用 go get 命令安装这两个库:
go get golang.org/x/crypto/ssh
go get github.com/pkg/sftp
原文地址: https://www.cveoy.top/t/topic/ozoc 著作权归作者所有。请勿转载和采集!