78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
package utils
|
|
|
|
import (
|
|
gossh "golang.org/x/crypto/ssh"
|
|
"log"
|
|
"net"
|
|
)
|
|
|
|
// Cli 连接信息
|
|
type Cli struct {
|
|
User string
|
|
Pwd string
|
|
Addr string
|
|
Client *gossh.Client
|
|
Session *gossh.Session
|
|
LastResult string
|
|
}
|
|
|
|
// Connect 连接对象
|
|
func (c *Cli) Connect() (*Cli, error) {
|
|
config := &gossh.ClientConfig{}
|
|
config.SetDefaults()
|
|
config.User = c.User
|
|
config.Auth = []gossh.AuthMethod{gossh.Password(c.Pwd)}
|
|
config.HostKeyCallback = func(hostname string, remote net.Addr, key gossh.PublicKey) error { return nil }
|
|
client, err := gossh.Dial("tcp", c.Addr, config)
|
|
if nil != err {
|
|
return c, err
|
|
}
|
|
c.Client = client
|
|
return c, nil
|
|
}
|
|
|
|
func (c *Cli) ConnectWithPrivateKey() (*Cli, error) {
|
|
// 解析私钥字符串
|
|
privateKey, err := gossh.ParsePrivateKey([]byte(c.Pwd))
|
|
if err != nil {
|
|
log.Fatalf("Failed to parse private key: %v", err)
|
|
}
|
|
|
|
// 配置 SSH 连接参数
|
|
config := &gossh.ClientConfig{
|
|
User: c.User,
|
|
Auth: []gossh.AuthMethod{
|
|
gossh.PublicKeys(privateKey),
|
|
},
|
|
HostKeyCallback: gossh.InsecureIgnoreHostKey(),
|
|
}
|
|
|
|
// 建立 SSH 连接
|
|
client, err := gossh.Dial("tcp", c.Addr+":22", config)
|
|
if err != nil {
|
|
log.Fatalf("无法建立 SSH 连接: %v", err)
|
|
}
|
|
|
|
c.Client = client
|
|
return c, nil
|
|
}
|
|
|
|
// Run 执行shell
|
|
func (c Cli) Run(shell string) (string, error) {
|
|
if c.Client == nil {
|
|
if _, err := c.Connect(); err != nil {
|
|
return "", err
|
|
}
|
|
}
|
|
session, err := c.Client.NewSession()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
// 关闭会话
|
|
defer session.Close()
|
|
buf, err := session.CombinedOutput(shell)
|
|
|
|
c.LastResult = string(buf)
|
|
return c.LastResult, err
|
|
}
|