天天看點

golang編寫ssh包

編寫遠端連接配接基礎包:

[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
}           

複制

引用:

[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)
}           

複制

結果:

[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           

複制