Golang实现一个批量自动化执行树莓派指令的软件(2)指令
package sshutil
import (
"fmt"
"golang.org/x/crypto/ssh"
"sync"
"testing"
"time"
)
func newCommander() (*Commander, error) {
config := &ssh.ClientConfig{
User: "pi",
Auth: []ssh.AuthMethod{
ssh.Password("a123456"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
sshCfg := SSHConfig{
IP: "192.168.3.2",
Port: 22,
User: "pi",
Password: "a123456",
sshClientConfig: config,
}
commander, err := NewCommander(sshCfg)
return commander, err
}
func TestEasyCommandAndDestroy(t *testing.T) {
commander, err := newCommander()
if nil != err {
fmt.Println("new command fail: ", err.Error())
return
}
defer func() {
e := commander.Destroy()
if nil != err {
fmt.Println("fail to destroy, ", e.Error())
}
}()
var output string
output, err = commander.Command("ls /")
fmt.Println("command result: ", output)
}
func TestCommandWithCallbackWithoutAsync(t *testing.T) {
commander, err := newCommander()
if nil != err {
fmt.Println("new command fail: ", err.Error())
return
}
defer func() {
e := commander.Destroy()
if nil != err {
fmt.Println("fail to destroy, ", e.Error())
}
}()
err = commander.CommandWithCallback("sleep 4; ls /", func(output string, e error) {
if nil != e {
fmt.Println("fail, ", e.Error())
} else {
fmt.Println("result: ", output)
}
}, false)
if nil != err {
fmt.Println("do command fail: ", err.Error())
return
}
}
func TestCommandWithCallbackAsync(t *testing.T) {
var waiter sync.WaitGroup
commander, err := newCommander()
if nil != err {
fmt.Println("new command fail: ", err.Error())
return
}
defer func() {
e := commander.Destroy()
if nil != err {
fmt.Println("fail to destroy, ", e.Error())
}
}()
waiter.Add(1)
err = commander.CommandWithCallback("sleep 4; ls /", func(output string, e error) {
if nil != e {
fmt.Println("fail, ", e.Error())
} else {
fmt.Println("result: ", output)
}
waiter.Done()
}, true)
if nil != err {
fmt.Println("do command fail: ", err.Error())
return
}
fmt.Println("waiting finished<--------")
waiter.Wait()
fmt.Println("waiting finished------>")
}
func TestCommandWithCallbackAndCancel(t *testing.T) {
var waiter sync.WaitGroup
commander, err := newCommander()
if nil != err {
fmt.Println("new command fail: ", err.Error())
return
}
defer func() {
e := commander.Destroy()
if nil != err {
fmt.Println("fail to destroy, ", e.Error())
}
}()
waiter.Add(1)
err = commander.CommandWithCallback("sleep 10; ls /", func(output string, e error) {
if nil != e {
fmt.Println("fail, ", e.Error())
} else {
fmt.Println("result: ", output)
}
waiter.Done()
}, true)
if nil != err {
fmt.Println("do command fail: ", err.Error())
return
}
fmt.Println("waiting finished<--------")
time.Sleep(time.Second * 2)
fmt.Println("canceling...")
fmt.Println("canceled, ", commander.Cancel())
waiter.Wait()
fmt.Println("waiting finished------>")
}