You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.2 KiB

package SshUtil
import (
"fmt"
"golang.org/x/crypto/ssh"
"net"
"time"
)
type Cli struct {
IP string
Username string
Password string
Port int
client *ssh.Client
LastResult string
}
func New(ip string, username string, password string, port ...int) *Cli {
cli := new(Cli)
cli.IP = ip
cli.Username = username
cli.Password = password
if len(port) <= 0 {
cli.Port = 22
} else {
cli.Port = port[0]
}
return cli
}
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 (c *Cli) connect() error {
config := ssh.ClientConfig{
User: c.Username,
Auth: []ssh.AuthMethod{ssh.Password(c.Password)},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
Timeout: 10 * time.Second,
}
addr := fmt.Sprintf("%s:%d", c.IP, c.Port)
sshClient, err := ssh.Dial("tcp", addr, &config)
if err != nil {
return err
}
c.client = sshClient
return nil
}