-
-
Save dalitun/9beef41767b2c009994fcf2b56cf01b1 to your computer and use it in GitHub Desktop.
Go lang SSH connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"code.google.com/p/go.crypto/ssh" | |
"fmt" | |
"io/ioutil" | |
"os" | |
) | |
func main() { | |
pk, _ := ioutil.ReadFile(os.Getenv("HOME") + "/.ssh/id_rsa") | |
signer, err := ssh.ParsePrivateKey(pk) | |
if err != nil { | |
panic(err) | |
} | |
config := &ssh.ClientConfig{ | |
User: "root", | |
Auth: []ssh.AuthMethod{ | |
ssh.PublicKeys(signer), | |
}, | |
} | |
client, err := ssh.Dial("tcp", "hostname:22", config) | |
if err != nil { | |
panic("Failed to dial: " + err.Error()) | |
} | |
// Each ClientConn can support multiple interactive sessions, | |
// represented by a Session. | |
session, err := client.NewSession() | |
if err != nil { | |
panic("Failed to create session: " + err.Error()) | |
} | |
defer session.Close() | |
// Once a Session is created, you can execute a single command on | |
// the remote side using the Run method. | |
var b bytes.Buffer | |
session.Stdout = &b | |
if err := session.Run("ls"); err != nil { | |
panic("Failed to run: " + err.Error()) | |
} | |
fmt.Println(b.String()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment