melbahja/goph

ssh: handshake failed: knownhosts: key is unknown exit status 1

kiransterling opened this issue · 4 comments

Not able to ssh to EC2 instance . Below is the error
ssh: handshake failed: knownhosts: key is unknown
exit status 1

package main

import (
"fmt"
"log"

"github.com/melbahja/goph"

)

func main() {

// Start new ssh connection with private key.
auth, err := goph.Key("{YOUR_PRIVATE_KEY}", "")
if err != nil {
	log.Fatal(err)
}

client, err := goph.New("ec2-user", "{YOUR_PUBLIC_IP}", auth)
if err != nil {
	log.Fatal(err)
}

// Defer closing the network connection.
defer client.Close()

// Execute your command.
out, err := client.Run("pwd")

if err != nil {
	log.Fatal(err)
}

// Get your output as []byte.
fmt.Println(string(out))

}

That's because the public key is not a known host, the public ip not in known_hosts file or ⚠️ public key mismatch.

Before you can connect to a new host you should trust the host public key first with: goph.AddKnownHost method.

The goph.AddKnownHost it will append a new line in your known_hosts file.

Can you update the code in readme file with goph.AddKnownHost usage.

You could possibly ignore the KnownHost if you want.
Ex:

_, err = goph.DefaultKnownHosts()

	if err != nil {
		return
	}

	c, err = goph.NewConn(&goph.Config{
		User:     user,
		Addr:     addr,
		Port:     port,
		Auth:     auth,
		Timeout:  goph.DefaultTimeout,
		Callback: ssh.InsecureIgnoreHostKey(),
	})