這是上述實施例的變形/完整版本https://godoc.org/golang.org/x/crypto/ssh#example-Dial
首先通過go get golang.org/x/crypto/ssh
得到terminal
包
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"strings"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
if len(os.Args) < 3 {
usage := "\n./remote-ssh {host} {port}"
fmt.Println(usage)
} else {
host := os.Args[1]
port := os.Args[2]
username, password := credentials()
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
}
connectingMsg := fmt.Sprintf("\nConnecting to %s:%v remote server...", host, port)
fmt.Println(connectingMsg)
hostAddress := strings.Join([]string{host, port}, ":")
// fmt.Println("Host add %s ", hostAddress)
client, err := ssh.Dial("tcp", hostAddress, config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
for {
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
// Once a Session is created, can execute a single command on remote side
var cmd string
str := "\nEnter command (e.g. /usr/bin/whoami OR enter 'exit' to return) : "
fmt.Print(str)
fmt.Scanf("%s", &cmd)
if cmd == "exit" || cmd == "EXIT" {
break
}
s := fmt.Sprintf("Wait for command '%s' run and response...", cmd)
fmt.Println(s)
var b bytes.Buffer
session.Stdout = &b
if err := session.Run(cmd); err != nil {
panic("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}
}
}
func credentials() (string, string) {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Username: ")
username, _ := reader.ReadString('\n')
fmt.Print("Enter Password: ")
bytePassword, err := terminal.ReadPassword(0)
if err != nil {
panic(err)
}
password := string(bytePassword)
return strings.TrimSpace(username), strings.TrimSpace(password)
}
https://play.golang.org/p/4Ad1vKNXmI
你不能用'ssh'很容易做到這一點,因爲它會拒絕從'stdin'讀取密碼。請參閱http://stackoverflow.com/q/1340366。您的最佳選擇似乎是生成密鑰對並使用它進行身份驗證。 –
我曾嘗試在Python中做到這一點。我只能使用[Paramiko](http://www.lag.net/paramiko/)工作。你應該試試[go.crypto/ssh](http://godoc.org/code.google.com/p/go.crypto/ssh)。 –
你似乎知道如何處理一個子進程的stdin和stdout就好了。該問題不在你的代碼中,但是由於ssh在檢測到它沒有在shell或tty中運行時具有不同的行爲。你將不得不使用證書認證而不是密碼。 –