I found this answer before posting this question but the answer is not clear to me.
这是答案的代码:
conn, err := ssh.Dial("tcp", hostname+":22", config)
if err != nil {
return err
}
session, err := conn.NewSession()
if err != nil {
return err
}
defer session.Close()
r, err := session.StdoutPipe()
if err != nil {
return err
}
name := fmt.Sprintf("%s/backup_folder_%v.tar.gz", path, time.Now().Unix())
file, err := os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
defer file.Close()
if err := session.Start(cmd); err != nil {
return err
}
n, err := io.Copy(file, r)
if err != nil {
return err
}
if err := session.Wait(); err != nil {
return err
}
return nil
我不了解cmd变量和io.Copy之间的关系,它在哪里以及如何知道要复制哪个文件。 我喜欢使用io.Copy的想法,但我不知道如何通过ssh创建文件并开始使用io.Copy向其发送内容。
答案 0 :(得分:2)
以下是有关如何将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的请求添加了等待组
答案 1 :(得分:2)
您也可以使用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"