码迷,mamicode.com
首页 > 其他好文 > 详细

go ssh 执行命令

时间:2019-01-28 19:14:58      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:pac   fun   shel   printf   set   \n   UNC   connect   lan   

go ssh 执行命令
package main

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

type Cli struct {
   user    string
   pwd     string
   addr    string
   client  *gossh.Client
   session *gossh.Session
   LastResult string     
}

func (c *Cli) Connect() (*Cli, error) {
   config := &gossh.ClientConfig{}
   config.SetDefaults()
   config.User = c.user
   config.Auth = []gossh.AuthMethod{gossh.Password(c.pwd)}
   config.HostKeyCallback = func(hostname string, remote net.Addr, key gossh.PublicKey) error { return nil }
   client, err := gossh.Dial("tcp", c.addr, config)
   if nil != err {
      return c, err
   }
   c.client = client
   return c, nil
}

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 main() {
   cli := Cli{
      user:"root",
      pwd: "xxxxxxxxxxxxxxxxxxxxx",
      addr: "192.168.100.50:22",
   }
   output, err := cli.Run("pwd")
   fmt.Printf("%v\n%v", output, err)
}

go ssh 执行命令

标签:pac   fun   shel   printf   set   \n   UNC   connect   lan   

原文地址:http://blog.51cto.com/hequan/2347357

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!