官方地址:https://godoc.org/golang.org/x/crypto/ssh

    1. package main
    2. import (
    3. "fmt"
    4. gossh "golang.org/x/crypto/ssh"
    5. "net"
    6. )
    7. type Cli struct {
    8. user string
    9. pwd string
    10. addr string
    11. client *gossh.Client
    12. session *gossh.Session
    13. LastResult string
    14. }
    15. func (c *Cli) Connect() (*Cli, error) {
    16. config := &gossh.ClientConfig{}
    17. config.SetDefaults()
    18. config.User = c.user
    19. config.Auth = []gossh.AuthMethod{gossh.Password(c.pwd)}
    20. config.HostKeyCallback = func(hostname string, remote net.Addr, key gossh.PublicKey) error { return nil }
    21. client, err := gossh.Dial("tcp", c.addr, config)
    22. if nil != err {
    23. return c, err
    24. }
    25. c.client = client
    26. return c, nil
    27. }
    28. func (c Cli) Run(shell string) (string, error) {
    29. if c.client == nil {
    30. if _,err := c.Connect(); err != nil {
    31. return "", err
    32. }
    33. }
    34. session, err := c.client.NewSession()
    35. if err != nil {
    36. return "", err
    37. }
    38. defer session.Close()
    39. buf, err := session.CombinedOutput(shell)
    40. c.LastResult = string(buf)
    41. return c.LastResult, err
    42. }
    43. func main() {
    44. cli := Cli{
    45. user:"root",
    46. pwd: "xxxxxxxxxxxxxxxxxxxxx",
    47. addr: "192.168.100.50:22",
    48. }
    49. output, err := cli.Run("pwd")
    50. fmt.Printf("%v\n%v", output, err)
    51. }