I have a requirement that I need to implement ssh to use public key to log in without password. I checked a lot of information on the Internet, but I didn't find the realization of this aspect, so I recorded it.
There is SSH_AUTH_SOCK environment variable on the SSH_AUTH_SOCK , this 060e9306be67e9 environment variable needs ssh-agent command, and secondly, the code is unclear or white and cannot run at all, so I just gave up.
That piece of code is as follows:

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)   //这个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 searching for a long time, I finally found a reference point example_test.go
The following is my implementation, available for pro-test. Everyone is 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
}

禹鼎侯
176 声望466 粉丝

OLAP数据库开发。跨平台数据采集。