gpt4 book ai didi

networking - Golang使用sftp golang库将远程文件复制到本地文件夹

转载 作者:IT王子 更新时间:2023-10-29 00:52:23 26 4
gpt4 key购买 nike

我得到了在远程主机上创建文件的代码:

config := &ssh.ClientConfig{
User: "xx",
HostKeyCallback: nil,
Auth: []ssh.AuthMethod{
ssh.Password("xx"),
},
}

config.SetDefaults()
sshConn, err := ssh.Dial("tcp", "192.xx.1.xx:22", config)
if err != nil {
panic(err)
}
defer sshConn.Close()

client, err := sftp.NewClient(sshConn)
if err != nil {
panic(err)
}
defer client.Close()

file, err := client.Create("/www/hello9.txt")
if err != nil {
panic(err)
}
defer file.Close()

if _, err := file.Write([]byte("Hello world")); err != nil {
log.Fatal(err)
}

但需要将文件从远程主机复制到本地主机。如何仅使用 golang 工具 github.com/pkg/sftpgolang.org/x/crypto/ssh 来实现这一点?

最佳答案

您可以使用 sftp 包中的 Open(path string)WriteTo(w io.Writer) 方法(当然您需要一个 os.文件或类似的东西写入)。

client, err := ssh.Dial("tcp", "192.x.x.x:22", sshConfig)
if err != nil {
panic("Failed to dial: " + err.Error())
}
fmt.Println("Successfully connected to ssh server.")

// open an SFTP session over an existing ssh connection.
sftp, err := sftp.NewClient(client)
if err != nil {
log.Fatal(err)
}
defer sftp.Close()

srcPath := "/tmp/"
dstPath := "C:/temp/"
filename := "test.txt"

// Open the source file
srcFile, err := sftp.Open(srcPath + filename)
if err != nil {
log.Fatal(err)
}
defer srcFile.Close()

// Create the destination file
dstFile, err := os.Create(dstPath + filename)
if err != nil {
log.Fatal(err)
}
defer dstFile.Close()

// Copy the file
srcFile.WriteTo(dstFile)

关于networking - Golang使用sftp golang库将远程文件复制到本地文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36786068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com