ssh_crawler/ssh/ssh.go

86 lines
1.5 KiB
Go
Raw Normal View History

2017-10-20 06:10:30 +00:00
package ssh
import (
2017-10-23 09:08:19 +00:00
"bytes"
2017-10-20 06:10:30 +00:00
"fmt"
"golang.org/x/crypto/ssh"
"strconv"
)
type SSHConfig struct {
User string
Auth []ssh.AuthMethod
Host string
Port int
}
type SSHClient struct {
2017-10-23 05:31:04 +00:00
session *ssh.Session
2017-10-23 09:08:19 +00:00
conf *SSHConfig
2017-10-20 06:10:30 +00:00
}
func New(ip, port, user, pw string) (*SSHClient, error) {
p, _ := strconv.Atoi(port)
2017-10-23 09:08:19 +00:00
conf := &SSHConfig{
2017-10-20 06:10:30 +00:00
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(pw),
},
Host: ip,
Port: p,
}
2017-10-23 09:08:19 +00:00
return &SSHClient{conf: conf}, nil
2017-10-20 06:10:30 +00:00
}
2017-10-23 05:31:04 +00:00
func (cli *SSHClient) Session() error {
2017-10-20 06:10:30 +00:00
sshConfig := &ssh.ClientConfig{
2017-10-23 09:08:19 +00:00
User: cli.conf.User,
Auth: cli.conf.Auth,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
2017-10-20 06:10:30 +00:00
}
2017-10-23 05:31:04 +00:00
connection, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", cli.conf.Host, cli.conf.Port), sshConfig)
2017-10-20 06:10:30 +00:00
if err != nil {
2017-10-23 09:08:19 +00:00
return err
2017-10-20 06:10:30 +00:00
}
session, err := connection.NewSession()
if err != nil {
2017-10-23 05:31:04 +00:00
return err
2017-10-20 06:10:30 +00:00
}
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()
2017-10-23 05:31:04 +00:00
return err
2017-10-20 06:10:30 +00:00
}
2017-10-23 05:31:04 +00:00
cli.session = session
2017-10-20 06:10:30 +00:00
2017-10-23 05:31:04 +00:00
return nil
2017-10-20 06:10:30 +00:00
}
func (cli *SSHClient) RunCommand(command string) ([]byte, error) {
2017-10-23 05:31:04 +00:00
if err := cli.Session(); err != nil {
2017-10-20 06:10:30 +00:00
return nil, err
}
2017-10-23 05:31:04 +00:00
var b bytes.Buffer
cli.session.Stdout = &b
2017-10-20 06:10:30 +00:00
2017-10-23 05:31:04 +00:00
err := cli.session.Run(command)
2017-10-20 06:10:30 +00:00
if err != nil {
return nil, err
}
2017-10-23 05:31:04 +00:00
cli.session.Close()
return b.Bytes(), nil
2017-10-20 06:10:30 +00:00
}