· 8 years ago · Jan 12, 2017, 05:56 PM
1// read private key
2 key, err := ioutil.ReadFile("/home/chris/.ssh/openwrt_rsa")
3 if err != nil {
4 panic(err)
5 }
6
7 // parse private key
8 signer, err := ssh.ParsePrivateKey(key)
9 if err != nil {
10 panic(err)
11 }
12
13 // ssh client configuration
14 config := &ssh.ClientConfig{
15 User: "root",
16 Auth: []ssh.AuthMethod{
17 ssh.PublicKeys(signer),
18 //ssh.Password("cool1125"),
19 },
20 }
21
22 // establish ssh connection
23 client, err := ssh.Dial("tcp", "192.168.1.1:22", config)
24 if err != nil {
25 panic(err)
26 }
27 defer client.Close()
28
29 // create new session
30 session, err := client.NewSession()
31 if err != nil {
32 panic(err)
33 }
34 defer session.Close()
35
36 var b bytes.Buffer
37 session.Stdout = &b
38 if err := session.Run("ls -al /"); err != nil {
39 panic("Failed to run: " + err.Error())
40 }
41 fmt.Println(b.String())