在使用gexpect包发现很多问题之外,这里又尝试使用ssh user@127.0.0.1的思路进行用户切换。这里记录下具体的使用方法,遇到的ssh: must specify HostKeyCallback 问题的解法方法及最终使用过程中的问题。

一、ssh包crypto的安装

ssh使用的包为"golang.org/x/crypto/ssh",由于golang.org被墙了,所以这里使用github上的镜像版本,所以这里不能使用go get进行安装(不要使用go get,不要使用go get,不要使用go get)。使用方法为git clone https://github.com/golang/crypto.git后,放到$GOPATH/src/golang.org/x/目录下面即可。

二、ssh登录代码
package main
import (
"golang.org/x/crypto/ssh"
"log"
"os"
)
func main() {
ce := func(err error, msg string) {
if err != nil {
log.Fatalf("%s error: %v", msg, err)
}
}
client, err := ssh.Dial("tcp", "127.0.0.1:22", &ssh.ClientConfig{
User: "zabbix",
Auth: []ssh.AuthMethod{ssh.Password("123456")},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
ce(err, "dial")
session, err := client.NewSession()
ce(err, "new session")
defer session.Close()
session.Stdout = os.Stdout
session.Stderr = os.Stderr
session.Stdin = os.Stdin
modes := ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
err = session.RequestPty("linux", 32, 160, modes)
ce(err, "request pty")
err = session.Shell()
ce(err, "start shell")
err = session.Wait()
ce(err, "return")
}

代码执行后,发现可以正常切换到对应的用户,而且命令重复输出的问题也解决了,但是tab不能补全命令,ps auxf查看不能全屏的问题依然存在

三、ssh: must specify HostKeyCallback报错解决

在执行上面的代码时可能会遇到ssh: must specify HostKeyCallback报错,出现该问题的原因是没有加如下行:

HostKeyCallback: ssh.InsecureIgnoreHostKey(),

除了增加上面的代码能解决外,也可以增加如下代码解决:

//需要验证服务端,不做验证返回nil就可以,点击HostKeyCallback看源码就知道了
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},

原文来自:http://www.361way.com/golang-ssh/5898.html

本文地址:https://www.linuxprobe.com/golang-ssh-used.html编辑:问题终结者,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/