Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Golang 使用ssh连接服务器
package main
import (
func main() {
var sshF = "/home/xiangchao/.ssh/id_rsa"
privateKey, err := ioutil.ReadFile(sshF)
if err != nil {
log.Printf("private key:\n %s", string(privateKey))
signer, err := ssh.ParsePrivateKey(privateKey)
if err != nil {
clientConfig := ssh.ClientConfig{
User: "micode",
Auth: []ssh.AuthMethod{
HostKeyCallback: func(
hostname string,
remote net.Addr,
key ssh.PublicKey) error {
// do something in call back function
return nil
client, err := ssh.Dial("tcp", "", &clientConfig)
if err != nil {
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.