Skip to content

Instantly share code, notes, and snippets.

@adam000
Last active July 13, 2016 18:09
Show Gist options
  • Save adam000/3f0e8559ea623ae9bd15792198095818 to your computer and use it in GitHub Desktop.
Save adam000/3f0e8559ea623ae9bd15792198095818 to your computer and use it in GitHub Desktop.
It took me a while to figure out how to run a sudo command (which requires an interactive console, in my case) with Go's SSH package. This is what I found.
package main
const (
sshKey string = "/Users/myuser/.ssh/id_rsa_mykey"
hostname string = "myhost.com"
)
package main
import (
"io/ioutil"
"log"
"os"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
key, err := ioutil.ReadFile(sshKey)
if err != nil {
panic(err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
panic(err)
}
authMethod := ssh.PublicKeys(signer)
config := &ssh.ClientConfig{
User: os.Getenv("LOGNAME"),
Auth: []ssh.AuthMethod{
authMethod,
},
}
conn, err := ssh.Dial("tcp", hostname+":22", config)
if err != nil {
panic(err)
}
session, err := conn.NewSession()
if err != nil {
panic(err)
}
defer session.Close()
modes := ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
log.Fatalf("request for pseudo terminal failed: %s", err)
}
session.Stdout = os.Stdout
session.Stderr = os.Stderr
session.Stdin = os.Stdin
terminal.MakeRaw(0)
session.Run("sudo touch hi")
log.Println("Done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment