验证中...
语言: Go
分类: 编程语言基础
最后更新于 2018-08-06 17:16
ssh 登录执行命令
原始数据 复制代码
package ssh
import (
"os"
"io"
"fmt"
"net"
"time"
"syscall"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
type Client struct {
user string
pass string
host string
port int
session *ssh.Session
}
func NewClient(user, pass, host string, port int) (client *Client, err error) {
client = &Client{user, pass, host, port, nil}
if err = client.connect(); err != nil {
return nil, err
}
return client, nil
}
func (c *Client) connect() (err error) {
var (
auth []ssh.AuthMethod
conf *ssh.ClientConfig
client *ssh.Client
)
auth = make([]ssh.AuthMethod, 0)
auth = append(auth, ssh.Password(c.pass))
conf = &ssh.ClientConfig{
User: c.user,
Auth: auth,
Timeout: 30 * time.Second,
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
if client, err = ssh.Dial("tcp", fmt.Sprintf("%s:%d", c.host, c.port), conf); err != nil {
return err
}
if c.session, err = client.NewSession(); err != nil {
return err
}
return nil
}
func (c *Client) Close() {
if c.session != nil {
c.session.Close()
}
}
func (c *Client) Run(shell string) (string, error) {
output, err := c.session.CombinedOutput(shell)
if err != nil {
return "", err
}
return string(output), nil
}
func (c *Client) RunTerminal(shell string, stdout, stderr io.Writer) (error) {
var fd int
if terminal.IsTerminal(syscall.Stdin) {
fd = syscall.Stdin
} else {
tty, err := os.Open("/dev/tty")
if err != nil {
return err
}
defer tty.Close()
fd = int(tty.Fd())
}
oldState, err := terminal.MakeRaw(fd)
if err != nil {
panic(err)
}
defer terminal.Restore(fd, oldState)
c.session.Stdout = stdout
c.session.Stderr = stderr
c.session.Stdin = os.Stdin
termWidth, termHeight, err := terminal.GetSize(fd)
if err != nil {
panic(err)
}
modes := ssh.TerminalModes{
ssh.ECHO: 1,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
if err := c.session.RequestPty("xterm-256color", termHeight, termWidth, modes); err != nil {
return err
}
c.session.Run(shell)
return nil
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助