Created
April 29, 2014 12:32
-
-
Save cloudaice/11398894 to your computer and use it in GitHub Desktop.
Golang 使用ssh连接服务器
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 ( | |
"io/ioutil" | |
"log" | |
"net" | |
"code.google.com/p/go.crypto/ssh" | |
) | |
func main() { | |
var sshF = "/home/xiangchao/.ssh/id_rsa" | |
privateKey, err := ioutil.ReadFile(sshF) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("private key:\n %s", string(privateKey)) | |
signer, err := ssh.ParsePrivateKey(privateKey) | |
if err != nil { | |
log.Fatal(err) | |
} | |
clientConfig := ssh.ClientConfig{ | |
User: "micode", | |
Auth: []ssh.AuthMethod{ | |
ssh.PublicKeys(signer), | |
}, | |
HostKeyCallback: func( | |
hostname string, | |
remote net.Addr, | |
key ssh.PublicKey) error { | |
// do something in call back function | |
return nil | |
}, | |
} | |
client, err := ssh.Dial("tcp", "micode.be.xiaomi.com:22", &clientConfig) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println("Connect Ok") | |
defer client.Close() | |
session, err := client.NewSession() | |
if err != nil { | |
log.Fatalf("Failed to create session: " + err.Error()) | |
} | |
log.Println("Get session OK") | |
defer session.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment