如何将密码传递给SSH?

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

How to feed a password to SSH?

问题

我需要使用基于密码的身份验证的scp来从服务器下载文件。如何使用Go实现这个功能?我尝试了以下代码,但它没有传递密码。

package main

import (
	"os/exec"
	"time"
)

func main() {
	password := "password"
	cmd := exec.Command("scp", "admin@192.168.1.150:file", "file")

	in, err := cmd.StdinPipe()
	if err != nil {
		panic(err)
	}

	defer in.Close()

	out, err := cmd.StdoutPipe()
	if err != nil {
		panic(err)
	}

	defer out.Close()

	if err = cmd.Run(); err != nil {
		panic(err)
	}

	go func() {
		time.Sleep(10 * time.Second)
		_, err = in.Write([]byte(password + "\n"))
		if err != nil {
			panic(err)
		}
	}()
}

编辑:我最终使用了gexpect(github.com/ThomasRooney/gexpect)库。

package main

import (
	"github.com/ThomasRooney/gexpect"
	"log"
)

func main() {
	child, err := gexpect.Spawn("scp admin@192.168.1.150:file file")
	if err != nil {
		log.Fatalln(err)
	}
	child.Expect("password:")
	child.SendLine("password")
	child.Interact()
	child.Close()
}

希望对你有帮助!

英文:

I need to use password authenticated scp to download a file from a server. How do I do so using Go? Tried the following code, but it doesn't pass in the password.

package main

import (
	"os/exec"
	"time"
)

func main() {
	password := "password"
	cmd := exec.Command("scp", "admin@192.168.1.150:file", "file")

	in, err := cmd.StdinPipe()
	if err != nil {
		panic(err)
	}

	defer in.Close()

	out, err := cmd.StdoutPipe()
	if err != nil {
		panic(err)
	}

	defer out.Close()

	if err = cmd.Run(); err != nil {
		panic(err)
	}

	go func() {
		time.Sleep(10 * time.Second)
		_, err = in.Write([]byte(password + "\n"))
		if err != nil {
			panic(err)
		}
	}()
}

Edit: I ended up using the gexpect (github.com/ThomasRooney/gexpect) library.

package main

import (
	"github.com/ThomasRooney/gexpect"
	"log"
)

func main() {
	child, err := gexpect.Spawn("scp admin@192.168.1.150:file file")
	if err != nil {
		log.Fatalln(err)
	}
	child.Expect("password:")
	child.SendLine("password")
	child.Interact()
	child.Close()
}

答案1

得分: 1

这个自问自答的问题的答案可能会有所帮助:

https://stackoverflow.com/questions/23019890/golang-write-input-and-get-output-from-terminal-process

至少,在答案中他提到他“能够通过密码获得ssh访问权限”,这在问题中没有明确提到 - 这就是为什么你在搜索网站时可能没有找到它的原因。

英文:

The answer to this self-answered question might help:

https://stackoverflow.com/questions/23019890/golang-write-input-and-get-output-from-terminal-process

at least, he mentions in the answer that he "was able to get ssh access working with a password", which is not mentioned explicitly in the question - that's why you probably didn't find it while searching the site?

huangapple
  • 本文由 发表于 2015年3月1日 03:56:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/28786190.html
匿名

发表评论

匿名网友

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

确定