有的时候我们不只是进行单纯的上传, 下载, 指令, 而是多个动作的组合操作
batch.go
package client
import (
"errors"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
type BatchCode int
const (
R_COMMAND = BatchCode(0) + iota
R_DOWNLOAD
R_UPLOAD
)
type UDInfo struct {
RemotePath string
LocalPath string
}
type Command struct {
Cmd string
}
type Mission struct {
BatchCode BatchCode
Info interface{}
}
type Batch interface {
RunBatch(ms []*Mission) error
}
type batch struct {
done uint
sshClient *ssh.Client
sftpClient *sftp.Client
}
func (b *batch) RunBatch(ms []*Mission) error {
b.done = 0
for _, m := range ms {
switch m.BatchCode {
case R_COMMAND : if err := b.runCommand(m.Info.(Command).Cmd); nil != err { return err }
case R_UPLOAD : if err := b.runUpload(m.Info.(UDInfo)); nil != err { return err }
case R_DOWNLOAD: if err := b.runDownload(m.Info.(UDInfo)); nil != err { return err }
default:
return errors.New("unsupport")
}
b.done += 1
}
return nil
}
func (b *batch) runCommand(cmd string) (err error) {
var c = commander{b.sshClient}
_, err = c.RunCommand(cmd)
return
}
func (b *batch) runUpload(info UDInfo) error {
var up = uploader{
sftpClient: b.sftpClient,
}
return up.Upload(info.LocalPath, info.RemotePath)
}
func (b *batch) runDownload(info UDInfo) error {
var down = downloader{
sftpClient: b.sftpClient,
}
return down.Download(info.RemotePath, info.LocalPath)
}
package client
import (
"fmt"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"net"
"testing"
"time"
)
func TestBatch_RunBatch(t *testing.T) {
config := ssh.ClientConfig{
User: "root", // 用户名
Auth: []ssh.AuthMethod{ssh.Password("xxxx")}, // 密码
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
Timeout: 10 * time.Second,
}
sshClient, err := ssh.Dial("tcp",
"192.168.31.75:22", &config) //IP + 端口
if err != nil {
fmt.Print(err)
return
}
defer sshClient.Close()
var sftpClient *sftp.Client
if sftpClient, err = sftp.NewClient(sshClient); err != nil {
return
}
defer sftpClient.Close()
var bat = &batch{sshClient: sshClient, sftpClient: sftpClient}
var ms = make([]*Mission, 0)
ms = append(ms, &Mission{BatchCode: R_COMMAND, Info: Command{Cmd: "ls"}})
ms = append(ms, &Mission{BatchCode: R_DOWNLOAD, Info: UDInfo{RemotePath: "/root/test", LocalPath: "./"}})
ms = append(ms, &Mission{BatchCode: R_UPLOAD, Info: UDInfo{RemotePath: "/root/", LocalPath: "CL/test"}})
err = bat.RunBatch(ms)
fmt.Println(err)
}