导入ssh所需的jar包
import (
"golang.org/x/crypto/ssh"
)
// ExecuteRemoteCommand 使用 SSH 远程执行命令
// remoteHost: SSH 服务器地址,格式为 "x.x.x.x"
// remotePort: SSH 服务器端口,默认为 22
// remoteUser: SSH 用户名
// remotePassword: SSH 密码
// command: 要执行的远程命令
// 返回结果字符串以及错误
func ExecuteRemoteCommand(remoteHost string, remotePort int, remoteUser string, remotePassword string, command string) (result string, err error) {
// 创建 SSH 登陆配置
config := &ssh.ClientConfig{
Timeout: 1 * time.Second, // SSH 连接超时时间为1秒,如果SSH验证错误,则在1秒内返回,设置为尽量短的时间
User: remoteUser,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
config.Auth = []ssh.AuthMethod{ssh.Password(remotePassword)}
// dial 获取 SSH client
addr := fmt.Sprintf("%s:%d", remoteHost, remotePort)
sshClient, err := ssh.Dial("tcp", addr, config)
if err != nil {
logger.Errorf("Failed to create SSH client", err)
return "", err
}
defer sshClient.Close()
// 创建 SSH session
session, err := sshClient.NewSession()
if err != nil {
logger.Errorf("Failed to create SSH session", err)
return "", err
}
defer session.Close()
// 执行远程命令
combo, err := session.CombinedOutput(command)
if err != nil {
logger.Errorf("Failed to execute command [%s], reason: [%s]", command, combo)
return "", err
}
return string(combo), nil
}