ssh_crawler/ssh/ssh.go
insanity 1076082050 ing
2017-10-20 15:10:30 +09:00

101 lines
1.7 KiB
Go

package ssh
import (
"fmt"
"golang.org/x/crypto/ssh"
"bytes"
"git.loafle.net/overflow/ssh_crawler/stat"
"strconv"
)
type SSHConfig struct {
User string
Auth []ssh.AuthMethod
Host string
Port int
}
type SSHClient struct {
Session *ssh.Session
}
func New(ip, port, user, pw string) (*SSHClient, error) {
p, _ := strconv.Atoi(port)
info := &SSHConfig {
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(pw),
},
Host: ip,
Port: p,
}
session, err := info.Session()
if err != nil {
fmt.Errorf("%s", err)
return nil, err
}
return &SSHClient{
Session: session,
}, nil
}
func (info *SSHConfig) Session() (*ssh.Session, error) {
sshConfig := &ssh.ClientConfig{
User: info.User,
Auth: info.Auth,
HostKeyCallback:ssh.InsecureIgnoreHostKey(),
}
connection, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", info.Host, info.Port), sshConfig)
if err != nil {
return nil, err
}
session, err := connection.NewSession()
if err != nil {
return nil, err
}
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
session.Close()
return nil, err
}
return session, nil
}
func (cli *SSHClient) Close() {
cli.Session.Close()
}
func (cli *SSHClient) RunCommand(command string) ([]byte, error) {
var b bytes.Buffer
cli.Session.Stdout = &b
err := cli.Session.Run(command)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
func (cli *SSHClient) CPUStat()([]stat.CPUStat, error) {
cpu := &stat.CPUStat{}
b, err := cli.RunCommand(cpu.Command())
if err != nil {
return nil, err
}
return cpu.Parse(bytes.NewReader(b))
}