pcm-coordinator/common/ssh/ssh_util.go

71 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package ssh
import (
"fmt"
gossh "golang.org/x/crypto/ssh"
"io"
"log"
"net"
"os/exec"
)
// 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
}
// 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
}
func ExecCommand(strCommand string) string {
cmd := exec.Command("/bin/bash", "-c", strCommand)
stdout, _ := cmd.StdoutPipe()
errReader, _ := cmd.StderrPipe()
defer stdout.Close()
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
cmdReader := io.MultiReader(stdout, errReader)
outBytes, _ := io.ReadAll(cmdReader)
if err := cmd.Wait(); err != nil {
fmt.Println("err", err.Error())
}
return string(outBytes)
}