1

I used the following go code to open an ssh connection to a remote host

func ssh(keyname string, user string, address string) {
    cmd := exec.Command("ssh", "-tt", user+"@"+address, "-i", "~/"+keyname) 
    cmd.Stderr = os.Stderr
    cmd.Stdout = os.Stdout

    if err := cmd.Run(); err != nil {
        fmt.Println(err.Error())
    }
}
func main() {
    ssh("example.pem", "ubuntu", "192.169.0.1")
}

When i run the code i connect successully to the remote host and get a terminal, but when i type commands it doesn't show any outputs just hangs, tried to ssh normally via my terminal and everything is ok. Not sure if this is from my code or SSH

3
  • you're missing the type handler. and you need ssh package(pkg.go.dev/golang.org/x/crypto/ssh) maybe. Commented Sep 1, 2022 at 13:57
  • @JiangYD I avoided the ssh package route, because i thought i could do a simple exec. Commented Sep 1, 2022 at 16:26
  • 2
    You're not assigning anything to Stdin Commented Sep 1, 2022 at 16:30

2 Answers 2

1

Use following code

package main
import (
    "log"

    "golang.org/x/crypto/ssh"
    "golang.org/x/crypto/ssh/knownhosts"
)

func main() {
    // ssh config
    hostKeyCallback, err := knownhosts.New("/home/debian11/.ssh/known_hosts")
    if err != nil {
        log.Fatal(err)
    }
    config := &ssh.ClientConfig{
        User: "ubuntu",
        Auth: []ssh.AuthMethod{
            ssh.Password("password"),
        },
        HostKeyCallback: hostKeyCallback,
    }
    // connect to ssh server
    conn, err := ssh.Dial("tcp", "192.169.0.1:22", config)
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()
}

Above is for password based login. Some changes will be required for certificate based auth.

Further reading:

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a reason ssh exec doesn't work as expected?
0

Assigning os.stdin to Stdin solves this problem, subtle

func ssh(keyname string, user string, address string) {
    cmd := exec.Command("ssh", "-tt", user+"@"+address, "-i", "~/"+keyname)

    cmd.Stdin = os.Stdin
    cmd.Stderr = os.Stderr
    cmd.Stdout = os.Stdout

    if err := cmd.Run(); err != nil {
        fmt.Println(err.Error())
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.