feat: ssh包新增本地私钥连接免密效果

This commit is contained in:
TsMask
2024-03-09 17:53:32 +08:00
parent a0baf86360
commit 730bbbc8cc

View File

@@ -4,10 +4,13 @@ import (
"bytes"
"fmt"
"io"
"os"
"os/user"
"strings"
"sync"
"time"
"be.ems/src/framework/logger"
gossh "golang.org/x/crypto/ssh"
)
@@ -15,7 +18,7 @@ import (
type ConnSSH struct {
User string `json:"user"` // 主机用户名
Addr string `json:"addr"` // 主机地址
Port int `json:"port"` // SSH端口
Port int64 `json:"port"` // SSH端口
AuthMode string `json:"authMode"` // 认证模式0密码 1主机私钥
Password string `json:"password"` // 认证密码
PrivateKey string `json:"privateKey"` // 认证私钥
@@ -59,6 +62,7 @@ func (c *ConnSSH) NewClient() (*ConnSSH, error) {
signer, err = gossh.ParsePrivateKey([]byte(c.PrivateKey))
}
if err != nil {
logger.Errorf("NewClient parse private key => %s", err.Error())
return nil, err
}
config.Auth = []gossh.AuthMethod{gossh.PublicKeys(signer)}
@@ -68,6 +72,7 @@ func (c *ConnSSH) NewClient() (*ConnSSH, error) {
client, err := gossh.Dial(proto, addr, config)
if nil != err {
logger.Errorf("NewClient dial => %s", err.Error())
return c, err
}
c.Client = client
@@ -81,6 +86,33 @@ func (c *ConnSSH) Close() {
}
}
// NewClientByLocalPrivate 创建SSH客户端-本地私钥(~/.ssh/id_rsa)直连
//
// ssh.ConnSSH{
// User: "user",
// Addr: "192.168.x.x",
// Port: body.Port,
// }
func (c *ConnSSH) NewClientByLocalPrivate() (*ConnSSH, error) {
c.Port = 22
c.AuthMode = "1"
usr, err := user.Current()
if err != nil {
logger.Errorf("NewClientByLocal get current user => %s", err.Error())
return nil, err
}
// 读取用户默认的私钥文件
keyPath := fmt.Sprintf("%s/.ssh/id_rsa", usr.HomeDir)
key, err := os.ReadFile(keyPath)
if err != nil {
logger.Errorf("NewClientByLocal [%s] read private key => %s", usr.Username, err.Error())
return nil, err
}
c.PrivateKey = string(key)
return c.NewClient()
}
// RunCMD 执行单次命令
func (c *ConnSSH) RunCMD(cmd string) (string, error) {
if c.Client == nil {
@@ -90,11 +122,14 @@ func (c *ConnSSH) RunCMD(cmd string) (string, error) {
}
session, err := c.Client.NewSession()
if err != nil {
logger.Errorf("RunCMD failed to create session: => %s", err.Error())
return "", err
}
defer session.Close()
buf, err := session.CombinedOutput(cmd)
if err != nil {
logger.Errorf("RunCMD failed run command: => %s", err.Error())
}
c.LastResult = string(buf)
return c.LastResult, err
}