(新手快来看)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))
}

posted @ 2022-10-13 11:31  ReevesMeng  阅读(109)  评论(0编辑  收藏  举报