Golang ssh and Ping packets

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.