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) }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Learning Vue.js 2
Olga Filipova / Packt Publishing / 2017-1-5 / USD 41.99
About This Book Learn how to propagate DOM changes across the website without writing extensive jQuery callbacks code.Learn how to achieve reactivity and easily compose views with Vue.js and unders......一起来看看 《Learning Vue.js 2》 这本书的介绍吧!