I have a requirement to implement SSH with a public key for secret free login. Checked a lot of data on the net, did not find the realization about this aspect unexpectedly, so record once. Online there is the use of SSH_AUTH_SOCKET environment variable method to achieve, but one of the SSH_AUTH_SOCKET environment variable needs to use the ssh-agent command to generate, and the code is unclear, can not run at all, so it is directly abandoned. That code looks like this:

func SSHClient(hostport string, username string) (*ssh.Client, error) { sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err ! = nil { logrus.Infof("error login,details: %s",err.Error()) return nil,err} agent := agent.newClient (sock) // What is this agent.newClient? Signers, err := agent. signers () if err! = nil { logrus.Infof("error login,details: %s",err.Error()) return nil,err } auths := []ssh.AuthMethod{ssh.PublicKeys(signers...) } cfg := &ssh.ClientConfig{ User: username, Auth: auths, HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }, } cfg.SetDefaults() logrus.Infof("tcp dial to %s",hostport) client, err := ssh.Dial("tcp", hostport, cfg) if err ! = nil { logrus.Infof("error login,details: %s",err.Error()) return nil,err } return client, nil }

After a long search, I finally found a reference in the official example_test.go code. Here is my implementation, available for pro testing. Welcome to discuss:

func SSHConnect(user, host string, port int) (*ssh.Client, error) { var ( addr string clientConfig *ssh.ClientConfig client *ssh.Client err error ) homePath, err := os.UserHomeDir() if err ! = nil { return nil, err } key, err := ioutil.ReadFile(path.Join(homePath, ".ssh", "id_rsa")) if err ! = nil { return nil, err } signer, err := ssh.ParsePrivateKey(key) if err ! = nil { return nil, err } clientConfig = &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ ssh.PublicKeys(signer), }, Timeout: 30 * time.Second, HostKeyCallback: ssh.InsecureIgnoreHostKey(), } // connet to ssh addr = fmt.Sprintf("%s:%d", host, port) if client, err = ssh.Dial("tcp", addr, clientConfig); err ! = nil { err = errors.Wrapf(err, "") return nil, err } return client, nil }