remote.go 834 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package remote
  2. import "golang.org/x/crypto/ssh"
  3. // SSHClient 封装SSH连接配置
  4. type SSHClient struct {
  5. Id string
  6. Username string
  7. Password string
  8. Host string
  9. Port string
  10. client *ssh.Client
  11. }
  12. // NewSSHClient 创建SSH连接
  13. func NewSSHClient(Id, username, password, host, port string) (*SSHClient, error) {
  14. config := &ssh.ClientConfig{
  15. User: username,
  16. Auth: []ssh.AuthMethod{
  17. ssh.Password(password),
  18. },
  19. HostKeyCallback: ssh.InsecureIgnoreHostKey(),
  20. }
  21. client, err := ssh.Dial("tcp", host+":"+port, config)
  22. if err != nil {
  23. return nil, err
  24. }
  25. return &SSHClient{
  26. Id: Id,
  27. Username: username,
  28. Password: password,
  29. Host: host,
  30. Port: port,
  31. client: client,
  32. }, nil
  33. }
  34. // Close 关闭SSH连接
  35. func (c *SSHClient) Close() {
  36. if c.client != nil {
  37. c.client.Close()
  38. }
  39. }