Last active
August 30, 2021 07:40
-
-
Save anhnd3/0e990a308a47b5a1f7ddc4ecbe932f67 to your computer and use it in GitHub Desktop.
Golang ssh connection
This file contains 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