some_dev
some_dev

Reputation: 201

Golang SSH client error "unable to authenticate, attempted methods [none publickey], no supported methods remain"

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.

Upvotes: 7

Views: 9061

Answers (2)

Vivian K. Scott
Vivian K. Scott

Reputation: 882

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"
import "strconv"

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

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

Upvotes: 1

some_dev
some_dev

Reputation: 201

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.

Upvotes: 3

Related Questions