2 回答
TA贡献1876条经验 获得超7个赞
您也可以使用 sftp 包 - “github.com/pkg/sftp”
func SSHCopyFile(srcPath, dstPath string) error {
config := &ssh.ClientConfig{
User: "user",
Auth: []ssh.AuthMethod{
ssh.Password("pass"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, _ := ssh.Dial("tcp", "remotehost:22", config)
defer client.Close()
// open an SFTP session over an existing ssh connection.
sftp, err := sftp.NewClient(client)
if err != nil {
return err
}
defer sftp.Close()
// Open the source file
srcFile, err := os.Open(srcPath)
if err != nil {
return err
}
defer srcFile.Close()
// Create the destination file
dstFile, err := sftp.Create(dstPath)
if err != nil {
return err
}
defer dstFile.Close()
// write to file
if _, err := dstFile.ReadFrom(srcFile); err!= nil {
return err
}
return nil
}
然后像这样称呼它
SSHCopyFile("/path/to/local/file.txt", "/path/on/remote/file.txt")
这些是必需的包
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
TA贡献1777条经验 获得超10个赞
这是一个关于如何将 Go 作为scp客户端使用的最小示例:
config := &ssh.ClientConfig{
User: "user",
Auth: []ssh.AuthMethod{
ssh.Password("pass"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, _ := ssh.Dial("tcp", "remotehost:22", config)
defer client.Close()
session, _ := client.NewSession()
defer session.Close()
file, _ := os.Open("filetocopy")
defer file.Close()
stat, _ := file.Stat()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
hostIn, _ := session.StdinPipe()
defer hostIn.Close()
fmt.Fprintf(hostIn, "C0664 %d %s\n", stat.Size(), "filecopyname")
io.Copy(hostIn, file)
fmt.Fprint(hostIn, "\x00")
wg.Done()
}()
session.Run("/usr/bin/scp -t /remotedirectory/")
wg.Wait()
请注意,为了简洁起见,我忽略了所有错误。
session.StdinPipe()
将为远程主机创建一个可写管道。fmt.Fprintf(... "C0664 ...")
0664
将用权限、stat.Size()
大小和远程文件名来表示文件的开始filecopyname
。io.Copy(hostIn, file)
将 的内容file
写入hostIn
.fmt.Fprint(hostIn, "\x00")
将发出文件结束信号。session.Run("/usr/bin/scp -qt /remotedirectory/")
将运行 scp 命令。
编辑:根据 OP 的请求添加等待组
- 2 回答
- 0 关注
- 175 浏览
添加回答
举报