【发布时间】:2020-12-16 17:23:03
【问题描述】:
我正在尝试使用 AWS 提供的 PEM 密钥通过 Go 代码连接到远程 EC2 服务器。我可以使用 PEM 密钥通过命令行登录服务器。
到目前为止,我已经完成了以下工作。
package main
import (
"io"
"io/ioutil"
"os"
"time"
"golang.org/x/crypto/ssh"
)
func publicKey(path string) ssh.AuthMethod {
key, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
panic(err)
}
return ssh.PublicKeys(signer)
}
func runCommand(cmd string, conn *ssh.Client) {
sess, err := conn.NewSession()
if err != nil {
panic(err)
}
defer sess.Close()
sessStdOut, err := sess.StdoutPipe()
if err != nil {
panic(err)
}
go io.Copy(os.Stdout, sessStdOut)
sessStderr, err := sess.StderrPipe()
if err != nil {
panic(err)
}
go io.Copy(os.Stderr, sessStderr)
err = sess.Run(cmd) // eg., /usr/bin/whoami
if err != nil {
panic(err)
}
}
func main() {
config := &ssh.ClientConfig{
User: "ec2-user",
Auth: []ssh.AuthMethod{
publicKey("mykey"),
},
Timeout: 15 * time.Second,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := ssh.Dial("tcp", "remote-server:22", config)
if err != nil {
panic(err.Error())
}
defer conn.Close()
runCommand("whoami", conn)
}
我不断收到以下错误。我错过了什么?
panic: ssh: handshake failed: read tcp "localhost"->"remotehost:22": read: operation timed out
在上面的消息中,我用假名替换了实际机器的 IP 地址。
【问题讨论】: