我有一个关于如何从终端子进程(例如 ssh)发送输入和接收输出的问题。 python 中的一个例子是这样的:
如何为子进程提供密码并同时获取标准输出
我在 Golang 中找不到与上述工作方式类似的简单示例。
在 Golang 中,我想做这样的事情,但它似乎不起作用:
cmd := exec.Command("ssh", "[email protected]")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
stdin, _ := cmd.StdinPipe()
stdin.Write([]byte("password\n"))
cmd.Run()
然而;我不知道如何在 go 中执行此操作,因为每次执行此 ssh 命令时,我只能获得输出。我无法从代码中自动输入密码。
有人有写入终端进程(例如 ssh)的示例吗?如果有,请分享。
感谢上面的评论,我能够使用密码获得 ssh 访问权限。我使用了golang的ssh api库。这非常简单,因为我遵循了以下示例:
https://code.google.com/p/go/source/browse/ssh/example_test.go?repo=crypto
具体来说:
func ExampleDial() {
// An SSH client is represented with a ClientConn. Currently only
// the "password" authentication method is supported.
//
// To authenticate with the remote server you must pass at least one
// implementation of AuthMethod via the Auth field in ClientConfig.
config := &ClientConfig{
User: "username",
Auth: []AuthMethod{
Password("yourpassword"),
},
}
client, err := Dial("tcp", "yourserver.com:22", config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("/usr/bin/whoami"); err != nil {
panic("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)