hacb
hacb

Reputation: 195

Execute ssh in golang

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.

Upvotes: 1

Views: 4413

Answers (2)

hacb
hacb

Reputation: 195

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 !

Upvotes: 1

Shang Jian Ding
Shang Jian Ding

Reputation: 2146

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)
    }
}

Upvotes: 6

Related Questions