golang ssh client(1)

package main

import (
	"context"
	"fmt"
	"net"
	"time"

	"golang.org/x/crypto/ssh"
)

type Client struct {
	client *ssh.Client
	user   string
	ip     string
	port   string
}

type CommandInfo struct {
	Cmd           string
	IsInteractive bool
	EndPoint      string
}

type CommandResult struct {
	Cmd    CommandInfo
	Result string
}

func NewClient(ip, port, user, pwd string) (*Client, error) {
	sshcli, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", ip, port), &ssh.ClientConfig{

		User: user,
		Auth: []ssh.AuthMethod{
			ssh.Password(pwd),
		},
		HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error {
			return nil
		}),
		// Timeout 建立tcp连接的超时时间
		Timeout: time.Duration(10) * time.Second,
	})
	if err != nil {
		return nil, err
	}
	return &Client{
		client: sshcli,
		user:   user,
		ip:     ip,
		port:   port,
	}, nil
}

func (cli *Client) Close() error {
	return cli.client.Close()
}

func (cli *Client) Run(cmd string) error {
	session, err := cli.client.NewSession()
	if err != nil {
		fmt.Printf("client NewSession fialed ,err = %v \n", err.Error())
		return err
	}
	defer session.Close()
	return session.Run(cmd)
}

func (cli *Client) CombineOutput(cmd string) ([]byte, error) {
	session, err := cli.client.NewSession()
	if err != nil {
		fmt.Println(err.Error())
		return nil, err
	}
	defer session.Close()
	return session.CombinedOutput(cmd)
}

func (cli *Client) ExecuteWithShell(cmds []CommandInfo, timeout time.Duration) ([]CommandResult, error) {
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	s, _, err := CreateShell(ctx, cli)
	if err != nil {
		return nil, err
	}
	go func() {
		for {
			select {
			case <-ctx.Done():
				s.session.Close()
				return
			}
		}
	}()
	defer s.Close()

	output, err := s.ExecuteCommands(cmds)
	if err != nil {
		return nil, err
	}
	return output, nil
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值