remote.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package remote
  2. import (
  3. "fmt"
  4. "golang.org/x/crypto/ssh"
  5. )
  6. // SSHClient 封装SSH连接配置
  7. type SSHClient struct {
  8. Id string
  9. Username string
  10. Password string
  11. Host string
  12. Port string
  13. client *ssh.Client
  14. }
  15. // NewSSHClient 创建SSH连接
  16. func NewSSHClient(Id, username, password, host, port string) (*SSHClient, error) {
  17. config := &ssh.ClientConfig{
  18. User: username,
  19. Auth: []ssh.AuthMethod{
  20. ssh.Password(password),
  21. },
  22. HostKeyCallback: ssh.InsecureIgnoreHostKey(),
  23. }
  24. client, err := ssh.Dial("tcp", host+":"+port, config)
  25. if err != nil {
  26. return nil, fmt.Errorf("无法连接到服务器 %s: %v", host, err)
  27. }
  28. return &SSHClient{
  29. Id: Id,
  30. Username: username,
  31. Password: password,
  32. Host: host,
  33. Port: port,
  34. client: client,
  35. }, nil
  36. }
  37. // Close 关闭SSH连接
  38. func (c *SSHClient) Close() {
  39. if c.client != nil {
  40. c.client.Close()
  41. }
  42. }
  43. // RunCommand 在远程服务器上执行命令
  44. func (c *SSHClient) RunCommand(cmd string) (string, error) {
  45. session, err := c.client.NewSession()
  46. if err != nil {
  47. return "", err
  48. }
  49. defer session.Close()
  50. output, err := session.CombinedOutput(cmd)
  51. if err != nil {
  52. return "", fmt.Errorf("无法执行命令: %v", err)
  53. }
  54. return string(output), nil
  55. }