工作需要写了个Go小程序,需要ssh到host上,并执行ping包,检查host的网络是否通。简单版的如下:
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
"os"
)
func main() {
// get ssh client
addrPort := "10.42.10.11:22"
client, err := ssh.Dial("tcp", addrPort, &ssh.ClientConfig{
User: "root",
Auth: []ssh.AuthMethod{ssh.Password("123456")},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
if err != nil {
fmt.Fprintf(os.Stdout, "Failed to get ssh client %v\n", err)
os.Exit(0)
}
defer client.Close()
// connect host
session, err := client.NewSession()
if err != nil {
fmt.Fprintf(os.Stdout, "Failed to connect session \n")
os.Exit(0)
}
defer session.Close()
pingAccess := "ping -c 2 10.42.10.12 | grep '100% packet loss' | wc -l"
result, err := session.Output(pingAccess)
if err != nil || 49 == result[0] {
fmt.Fprintf(os.Stdout, "Failed to ping result:%d, Err:%v \n", result[0], err)
os.Exit(0)
}
//result is ASCII
fmt.Fprintf(os.Stdout, "finish %d \n", result[0])
}
简单的说明:
1. 下载crypto源码git clone https://github.com/golang/crypto.git,把crypto文件夹拷贝到vendor/golang.org/x/目录下
2. 这里的ssh.InsecureIgnoreHostKey是不检查host key,需要检查的话得参考client源码重写函数。
3. session.run(command)是直接在host执行命令,不关心执行结果。session.Output是将执行命令之后的Stdout返回
有疑问加站长微信联系(非本文作者)