ssh.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # encoding: utf-8
  2. import logging
  3. import subprocess
  4. from . import logger
  5. logger = logger.new(__name__)
  6. class StderrException(Exception):
  7. pass
  8. class SSHClient(object):
  9. def __init__(self, host, user, private_key_f, port=22):
  10. self.host = host
  11. self.port = port
  12. self.user = user
  13. self.private_key_file = private_key_f
  14. self.client = self.new_ssh_client()
  15. def get_host(self):
  16. return self.host
  17. def get_hostname(self):
  18. try:
  19. return self.exec_command('hostnamectl hostname').strip()
  20. except:
  21. return self.exec_command('hostname').strip()
  22. def get_user(self):
  23. return self.user
  24. def get_port(self):
  25. return self.port
  26. def get_private_key_file(self):
  27. return self.private_key_file
  28. def new_ssh_client(self):
  29. def cli_w(cmd):
  30. user_host = "%s@%s" % (self.get_user(), self.get_host())
  31. args = ["ssh",
  32. "-p", str(self.get_port()),
  33. "-o", "LogLevel=error",
  34. "-o", "StrictHostKeyChecking=no",
  35. "-o", "UserKnownHostsFile=/dev/null",
  36. "-o", "ForwardX11=no",
  37. "-i", self.get_private_key_file(),
  38. user_host,
  39. cmd]
  40. debug_args = [x for x in args]
  41. debug_args[-1] = "'%s'" % debug_args[-1]
  42. debug_cmd = ' '.join(debug_args)
  43. print(debug_cmd)
  44. ssh = subprocess.Popen(args,
  45. stdout=subprocess.PIPE,
  46. stderr=subprocess.PIPE)
  47. stdout, stderr = ssh.communicate()
  48. out = stdout.decode('utf-8')
  49. err = stderr.decode('utf-8')
  50. return out, err
  51. return cli_w
  52. # def new_ssh_client(self):
  53. # import paramiko
  54. #
  55. # k = paramiko.RSAKey.from_private_key_file(self.private_key_file)
  56. # c = paramiko.SSHClient()
  57. # c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  58. # c.connect(
  59. # hostname=self.host,
  60. # port=self.port,
  61. # username=self.user,
  62. # pkey=k,
  63. # banner_timeout=60,
  64. # timeout=60)
  65. # return c
  66. def exec_command(self, command, use_sudo=False):
  67. command = "bash -c '%s %s'" % ('[ -s /etc/kubernetes/admin.conf ] && export KUBECONFIG=/etc/kubernetes/admin.conf || :;', command)
  68. if use_sudo:
  69. command = f'sudo {command}'
  70. logger.info("exec_command: %s" % command)
  71. # _, stdout, stderr = self.client.exec_command(command)
  72. out, err = self.client(command)
  73. if err:
  74. raise StderrException(err)
  75. return out