Search code examples
sshgoforklang

Go Lang exec/spawn a ssh session


I'm trying to work out the mechanism to fork/start a ssh terminal session i.e I want to be logged into remote server (my keys are on server) if I execute this program.

Right now it just executes but nothing happens.

package main

import (
 "os/exec"   
 "os"
)

func main() {
  cmd := exec.Command("ssh","root@SERVER-IP")
  cmd.Stdout = os.Stdout
  //cmd.Stderr = os.Stderr
  cmd.Run()

}

Solution

  • cmd.Run waits for the command to complete. Your ssh session should (normally) not exit without user interaction. Therefore your program blocks, since it waits for the ssh process to finish.

    You may want to either

    • also redirect Stdin, so you can interact with the ssh session
    • execute ssh me@server somecommand. In the last form a specific command gets executed and the output of this command gets redirected.
    • take a look at the ssh package