Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang 使用ssh连接服务器
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
You can’t perform that action at this time.