英文:
How to create sftp client over exist ssh connection on golang
问题
大家好!我需要帮助。我试图在几分钟前创建的现有SSH客户端上创建一个新的SFTP连接,但是我无法成功。我不知道为什么。
以下是代码片段:
config := &ssh.ClientConfig{
User: *loginArg,
Auth: []ssh.AuthMethod{
ssh.Password(*passArg),
},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
addr := fmt.Sprintf("%s:%d", *ipArg, *portArg)
client, err := ssh.Dial("tcp", addr, config)
if err != nil {
fmt.Printf("连接失败:%s", err)
}
fmt.Println("成功连接到", *ipArg, ":", *portArg)
session, err := client.NewSession()
if err != nil {
fmt.Printf("创建新会话失败:%s", err)
}
defer session.Close()
b, err := session.CombinedOutput("/system backup save name=BackUp dont-encrypt=yes") // /system backup save name=BackUp dont-encrypt=yes
if err != nil {
fmt.Printf("发送输出命令失败:%s", err)
}
fmt.Print(string(b))
//*******************
var conn *ssh.Client
sftp, err := sftp.NewClient(conn)
//sftp, err := sftp.NewClient(conn) //err
if err != nil {
log.Fatal(err) //fmt.Printf("创建新的SFTP客户端失败:%s", err)
}
defer sftp.Close()
英文:
guys! I need help. I tried to create a new sftp connection over existing ssh client that i made few minutes ago. I can't. And idk why.
Here is a pie of code:
config := &ssh.ClientConfig{
User: *loginArg,
Auth: []ssh.AuthMethod{
ssh.Password(*passArg),
},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
addr := fmt.Sprintf("%s:%d", *ipArg, *portArg)
client, err := ssh.Dial("tcp", addr, config)
if err != nil {
fmt.Printf("Failed to dial: %s", err)
}
fmt.Println("Successfully connected to ", *ipArg, ":", *portArg)
session, err := client.NewSession()
if err != nil {
fmt.Printf("Failed to create a new session: %s", err)
}
defer session.Close()
b, err := session.CombinedOutput("/system backup save name=BackUp dont-encrypt=yes") // /system backup save name=BackUp dont-encrypt=yes
if err != nil {
fmt.Printf("Failed to send output command: %s", err)
}
fmt.Print(string(b))
//*******************
var conn *ssh.Client
sftp, err := sftp.NewClient(conn)
//sftp, err := sftp.NewClient(conn) //err
if err != nil {
log.Fatal(err) //fmt.Printf("Failed to create new sftp-client: %s", err)
}
defer sftp.Close()
答案1
得分: 0
找到答案:只需要使用client而不是conn:
client, err := ssh.Dial("tcp", addr, config)
sftp, err := sftp.NewClient(client)
英文:
Find the answer: just need client instead of conn:
client, err := ssh.Dial("tcp", addr, config)
sftp, err := sftp.NewClient(client)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论