(新手快来看)Go ssh登陆服务器执行指令基础代码
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
"log"
)
func main(){
sshconfig := ssh.ClientConfig{
User: "用户名",
Auth: []ssh.AuthMethod{ssh.Password("密码")},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
sshclient, err := ssh.Dial("tcp", "Ip地址:22", &sshconfig)
if err != nil {
log.Fatal("ssh连接登陆失败", err)
}
defer sshclient.Close()
sshsession, err := sshclient.NewSession()
if err != nil {
log.Fatal("ssh会话创建失败", err)
}
defer sshsession.Close()
sshresult, err := sshsession.CombinedOutput("df -h")
if err != nil {
log.Fatal("命令执行失败", err)
}
fmt.Println(string(sshresult))
}
博文欢迎转载,转载请注明出处