Go : ssh操作(五)功能集合

发布时间:2024年01月11日

简介

将指令,上传,下载,批处理,多有功能集中起来

代码

remoter.go

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://blog.csdn.net/halo_hsuh/article/details/135466815
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。