1

I'm looking for a way to launch ssh in a terminal from a golang program.

func main() {
    cmd := exec.Command("ssh", "[email protected]", "-p", "2222")
    err := cmd.Run()
    if err != nil {
            panic(err)
    }
}

This works great until I enter the correct password, then the program exits. I guess when authentified, another ssh script in launched, but I can't figure out how to solve this. I have searched some infos about it but all I found is how to create a ssh session in go, and I would like to avoid this, if possible.

4
  • 1
    So you don't want to use golang.org/x/crypto/ssh? Commented Apr 18, 2020 at 17:30
  • Exact, I'd like to avoid creating a session inside my program. I just want to launch it as if I launched it from my terminal. Commented Apr 18, 2020 at 17:31
  • I just noticed a little issue in your code. You can not just pass all the arguments in one variable. You need to do something like this exec.Command("ssh", "[email protected]", "-p" ,"2222") Commented Apr 18, 2020 at 17:38
  • You are right ! I will edit my post, thank you ! Commented Apr 18, 2020 at 17:39

2 Answers 2

6

You should pass in stdin, stdout, and stderr:

package main

import (
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("ssh", "[email protected]", "-p", "2222")
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    err := cmd.Run()
    if err != nil {
        panic(err)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I have found another way to solve my issue, by using :

binary, lookErr := exec.LookPath("ssh")
if lookErr != nil {
    panic(lookErr)
}
syscall.Exec(binary, []string{"ssh", "[email protected]", "-p", "2222"}, os.Environ())

This will close the program's process and launch ssh on another one. Thanks for helping me !

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.