如何在Golang中使用现有的SSH连接创建SFTP客户端

huangapple go评论148阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2017年7月15日 01:04:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/45108286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定