go 使用ssh远程连接服务器并执行命令
package main
import (
"fmt"
"log"
"net"
"time"
"golang.org/x/crypto/ssh"
)
// 连接的配置
type ClientConfig struct {
Host string //ip
Port int64 // 端口
Username string //用户名
Password string //密码
Client *ssh.Client //ssh client
LastResult string //最近一次运行的结果
}
func (cliConf *ClientConfig) createClient(host string, port int64, username, password string) {
var (
client *ssh.Client
err error
)
cliConf.Host = host
cliConf.Port = port
cliConf.Username = username
cliConf.Password = password
cliConf.Port = port
//一般传入四个参数:user,[]ssh.AuthMethod{ssh.Password(password)}, HostKeyCallback,超时时间,
config := ssh.ClientConfig{
User: cliConf.Username,
Auth: []ssh.AuthMethod{ssh.Password(password)},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
Timeout: 10 * time.Second,
}
addr := fmt.Sprintf("%s:%d", cliConf.Host, cliConf.Port)
//获取client
if client, err = ssh.Dial("tcp", addr, &config); err != nil {
log.Fatalln("error occurred:", err)
}
cliConf.Client = client
}
func (cliConf *ClientConfig) RunShell(shell string) string {
var (
session *ssh.Session
err error
)
//获取session,这个session是用来远程执行操作的
if session, err = cliConf.Client.NewSession(); err != nil {
log.Fatalln("error occurred:", err)
}
//执行shell
if output, err := session.CombinedOutput(shell); err != nil {
log.Fatalln("error occurred:", err)
} else {
cliConf.LastResult = string(output)
}
return cliConf.LastResult
}
func main() {
cliConf := new(ClientConfig)
cliConf.createClient("10.0.0.30", 22, "root", "111111")
/*
可以看到我们这里每次执行一条命令都会创建一条session
这是因为一条session默认只能执行一条命令
并且两条命令不可以分开写
比如:
cliConf.RunShell("cd /opt")
cliConf.RunShell("ls")
这两条命令是无法连续的,下面的ls查看的依旧是~目录
因此我们可以连着写,使用;分割
*/
fmt.Println(cliConf.RunShell("cd /opt; ls -l;pwd"))
fmt.Println(cliConf.RunShell("pwd"))
fmt.Println(cliConf.RunShell("ps -ef | grep 22"))
/*
total 20
drwxr-xr-x 3 root root 4096 Nov 18 14:05 hadoop
drwxr-xr-x 3 root root 4096 Nov 18 14:20 hive
drwxr-xr-x 3 root root 4096 Nov 18 15:07 java
drwxr-xr-x 3 root root 4096 Nov 4 23:01 kafka
drwxr-xr-x 3 root root 4096 Nov 4 22:54 zookeeper
*/
fmt.Println(cliConf.LastResult)
}
本文来自博客园,作者:厚礼蝎,转载请注明原文链接:https://www.cnblogs.com/guangdelw/p/17178226.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具