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 關注
- 207 瀏覽
添加回答
舉報