前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang编写ssh包

golang编写ssh包

作者头像
MySQL轻松学
发布2019-09-04 11:02:20
1.1K0
发布2019-09-04 11:02:20
举报
文章被收录于专栏:MYSQL轻松学

编写远程连接基础包:

代码语言:javascript
复制
[root@localhost ssh]# cat ssh.go 
package ssh

import (
    "fmt"
    "time"
    "net"
    "golang.org/x/crypto/ssh"
)

type Cli struct {
    IP         string      //IP地址
    Username   string      //用户名
    Password   string      //密码
    Port       int         //端口号
    client     *ssh.Client //ssh客户端
    LastResult string      //最近一次Run的结果
}

//创建命令行对象
//@param ip IP地址
//@param username 用户名
//@param password 密码
//@param port 端口号,默认22
func Ssh(ip string, username string, password string, port ...int) *Cli {
    cli := new(Cli)
    cli.IP = ip
    cli.Username = username
    cli.Password = password
    if len(port) <= 0 {
        cli.Port = 22
    } else {
        cli.Port = port[0]
    }
    return cli
}

//执行shell
//@param shell shell脚本命令
func (c Cli) Run(shell string) (string, error) {
    if c.client == nil {
        if err := c.connect(); err != nil {
            return "", err
        }
    }
    session, err := c.client.NewSession()
    if err != nil {
        return "", err
    }
    defer session.Close()
    buf, err := session.CombinedOutput(shell)
 
    c.LastResult = string(buf)
    return c.LastResult, err
}

//连接
func (c *Cli) connect() error {
    config := ssh.ClientConfig{
        User: c.Username,
        Auth: []ssh.AuthMethod{ssh.Password(c.Password)},
        HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
            return nil
        },
        Timeout: 10 * time.Second,
    }
    addr := fmt.Sprintf("%s:%d", c.IP, c.Port)
    sshClient, err := ssh.Dial("tcp", addr, &config)
    if err != nil {
        return err
    }
    c.client = sshClient
    return nil
}

引用:

代码语言:javascript
复制
[root@localhost get_disk]# cat Get_Disk.go 
package main

import (
    "fmt"
    "../ssh"
)

func main() {
    cli := ssh.Ssh("1.1.1.1", "root", "xxx", 22)
    output, err := cli.Run("df -h")
    fmt.Printf("%v\n%v", output, err)
}

结果:

代码语言:javascript
复制
[root@localhost get_disk]# go build Get_Disk.go 
[root@localhost get_disk]# ./Get_Disk 
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3       258G  3.1G  242G   2% /
tmpfs            63G     0   63G   0% /dev/shm
/dev/sda1       488M   56M  407M  12% /boot
/dev/sdb1       2.9T  2.0T  756G  73% /export
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-09-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 MYSQL轻松学 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档