Home > other >  Golang SSH client error "unable to authenticate, attempted methods [none publickey], no support
Golang SSH client error "unable to authenticate, attempted methods [none publickey], no support

Time:06-22

For some reason Golang SSH client can't connect to my EC2 instance. It throws the following error:
ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

This is my code:

package main

import (
    "fmt"

    "github.com/helloyi/go-sshclient"
)

func main() {
    client, err := sshclient.DialWithKey("ip:port", "ubuntu", "my_key.pem")
    if err != nil {
        fmt.Println(err)
        return
    }

    out, err := client.Cmd("help").Output()
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(string(out))
}

What's interesting is that when I ran this code on my other computer the connection was made without any errors. So I think it must be a problem with the PC and not my code. I also tried connecting to the instance in Python using Paramiko client and it worked flawlessly. Of course I tried connecting using ssh command in CMD and MobaXTerm client - both worked. I tried using other Golang SSH client golang.org/x/crypto/ssh and it didn't work (same error).

Thank you for your help.

CodePudding user response:

assume you can ssh user@host without password, public key may be ~/.ssh/id_rsa or ~/.ssh/id_ecda

import "golang.org/x/crypto/ssh"
import "io/ioutil"

func DialWithPublickey(addr string, port int, user, publickeyfile string) (*ssh.Client, error) {
    if key, err := ioutil.ReadFile(publickeyfile); err == nil {
        if signer, err := ssh.ParsePrivateKey(key); err == nil {
            config := &ssh.ClientConfig{
                User: user,
                Auth: []ssh.AuthMethod{
                    ssh.PublicKeys(signer),
                },
                HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, publickey ssh.PublicKey) error { return nil }),
            }
            if client, err := ssh.Dial("tcp", addr ":" strconv.Itoa(port), config); client != nil && err == nil {
                client.SendRequest(user "@" addr, true, nil) // keep alive
                return client, nil
            }
            return nil, err
        } else {
            return nil, err
        }
    } else {
        return nil, err
    }
}

try DialWithPublickey(host, port, user, "~/.ssh/id_rsa")

CodePudding user response:

Apparently, it was an issue with go.mod file. Both golang.org/x/crypto and golang.org/x/sys were outdated, once I updated them it started working. Thanks @kkleejoe for your help.

  • Related