我对如何从ssh等终端子进程发送输入和接收输出有疑问。
我在Golang中找不到一个简单的示例,其工作原理与上述类似。
在Golang中,我想做这样的事情,但是似乎不起作用:
cmd := exec.Command("ssh", "user@x.x.x.x") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr stdin, _ := cmd.StdinPipe() stdin.Write([]byte("password\n")) cmd.Run()
然而; 我不确定如何执行此操作,因为每次执行此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()) }