简体   繁体   中英

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", "user@192.168.0.17", "-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.

You should pass in stdin , stdout , and stderr :

package main

import (
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("ssh", "user@192.168.0.17", "-p", "2222")
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    err := cmd.Run()
    if err != nil {
        panic(err)
    }
}

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", "user@192.168.0.17", "-p", "2222"}, os.Environ())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM