package main
import (
"fmt"
gossh "golang.org/x/crypto/ssh"
"net"
)
// 连接信息
type Cli struct {
user string
pwd string
addr string
client *gossh.Client
session *gossh.Session
LastResult string
}
// 连接对象
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
}
// 执行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 main() {
cli := Cli{
addr: "127.0.0.1:22",
user: "root",
pwd: "123456",
}
// 建立连接对象
c,_ := cli.Connect()
// 退出时关闭连接
defer c.client.Close()
res ,_ := c.Run("ls")
res1 ,_ := c.Run("pwd")
fmt.Println(res)
fmt.Println(res1)
}