简介
将指令,上传,下载,批处理,多有功能集中起来
代码
remoter.go文章来源:https://www.toymoban.com/news/detail-821737.html
package client
import (
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
type Remoter struct {
Commander
Uploader
Downloader
Batch
sshClient *ssh.Client
sftpClient *sftp.Client
}
func NewRemoter(network string, addr string, config ssh.ClientConfig) (*Remoter, error) {
sshClient, err := ssh.Dial(network,
addr, &config) //IP + 端口
if err != nil {
return nil, err
}
var sftpClient *sftp.Client
if sftpClient, err = sftp.NewClient(sshClient); err != nil {
sshClient.Close()
return nil, err
}
var remoter = &Remoter{sshClient: sshClient, sftpClient: sftpClient}
remoter.Commander = &commander{sshClient: sshClient}
remoter.Uploader = &uploader{sftpClient: sftpClient}
remoter.Downloader = &downloader{sftpClient: sftpClient}
remoter.Batch = &batch{sshClient: sshClient, sftpClient: sftpClient}
return remoter, nil
}
测试用例
package client
import (
"fmt"
"golang.org/x/crypto/ssh"
"net"
"testing"
"time"
)
func TestNewRemoter(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,
}
var remoter, err = NewRemoter("tcp", "192.168.31.75:22", config)
if nil != err {
fmt.Println(err)
return
}
remoter.RunCommand("ls")
remoter.Download("/root/test", "./")
remoter.Upload("C:/test", "/root/")
}
资源
整个项目代码 - https://download.csdn.net/download/halo_hsuh/12540666文章来源地址https://www.toymoban.com/news/detail-821737.html
到了这里,关于Go : ssh操作(五)功能集合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!