go ssh 执行命令
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go ssh 执行命令相关的知识,希望对你有一定的参考价值。
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
%v", output, err)
}
以上是关于go ssh 执行命令的主要内容,如果未能解决你的问题,请参考以下文章
[Go] 通过 17 个简短代码片段,切底弄懂 channel 基础
解决go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘(代码片段