This is a creation in Article, where the information may have evolved or changed.
Work needs to write a go applet, need to SSH to host, and execute ping packet, check whether the host network. The simple version is as follows:
package mainimport ("fmt""golang.org/x/crypto/ssh""os")func main() {// get ssh clientaddrPort := "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 hostsession, 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 ASCIIfmt.Fprintf(os.Stdout, "finish %d \n", result[0])}
A simple explanation:
1. Download the crypto source git clone https://github.com/golang/crypto.git and copy the Crypto folder to the vendor/golang.org/x/directory
2. SSH here. Insecureignorehostkey is not to check the host key, need to check the words to refer to the client source rewrite function.
3. Session.run (command) executes commands directly in host and does not care about execution results. Session. Output is the return of the stdout after executing the command