51 lines
1.0 KiB
Go
51 lines
1.0 KiB
Go
package app
|
|
|
|
import (
|
|
gossh "golang.org/x/crypto/ssh"
|
|
"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
|
|
}
|
|
|
|
// 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
|
|
}
|