__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from paramiko.client import SSHClient, AutoAddPolicy
  2. from paramiko.ssh_exception import AuthenticationException
  3. from paramiko.rsakey import RSAKey
  4. from apps.setting import Setting
  5. from io import StringIO
  6. def generate_ssh_key():
  7. key_obj = StringIO()
  8. key = RSAKey.generate(2048)
  9. key.write_private_key(key_obj)
  10. return key_obj.getvalue(), 'ssh-rsa ' + key.get_base64()
  11. def add_public_key(hostname, port, password):
  12. ssh_client = SSHClient()
  13. ssh_client.set_missing_host_key_policy(AutoAddPolicy)
  14. ssh_client.connect(
  15. hostname,
  16. port=port,
  17. username='root',
  18. password=password
  19. )
  20. try:
  21. _, stdout, stderr = ssh_client.exec_command('mkdir -p -m 700 /root/.ssh && \
  22. echo %r >> /root/.ssh/authorized_keys && \
  23. chmod 600 /root/.ssh/authorized_keys' % Setting.ssh_public_key)
  24. if stdout.channel.recv_exit_status() != 0:
  25. raise Exception('Add public key error: ' + ''.join(x for x in stderr))
  26. finally:
  27. ssh_client.close()
  28. def get_ssh_client(hostname, port):
  29. ssh_client = SSHClient()
  30. ssh_client.set_missing_host_key_policy(AutoAddPolicy)
  31. ssh_client.connect(
  32. hostname,
  33. port=port,
  34. username='root',
  35. pkey=RSAKey.from_private_key(StringIO(Setting.ssh_private_key)))
  36. return ssh_client
  37. def ssh_exec_command(hostname, port, command):
  38. ssh_client = get_ssh_client(hostname, port)
  39. try:
  40. _, stdout, stderr = ssh_client.exec_command(command)
  41. return stdout.channel.recv_exit_status(), ''.join(x for x in stdout), ''.join(x for x in stderr)
  42. except Exception as e:
  43. return 256, e, None
  44. finally:
  45. ssh_client.close()
  46. def ssh_exec_command_with_stream(ssh_client, command):
  47. try:
  48. _, stdout, _ = ssh_client.exec_command(command, get_pty=True)
  49. except Exception as e:
  50. ssh_client.close()
  51. raise e
  52. while True:
  53. message = stdout.readline()
  54. if not message:
  55. break
  56. yield message
  57. ssh_client.close()
  58. def ssh_ping(hostname, port):
  59. ssh_client = SSHClient()
  60. ssh_client.set_missing_host_key_policy(AutoAddPolicy)
  61. try:
  62. ssh_client.connect(
  63. hostname,
  64. port=port,
  65. username='root',
  66. pkey=RSAKey.from_private_key(StringIO(Setting.ssh_private_key)))
  67. except AuthenticationException:
  68. return False
  69. ssh_client.close()
  70. return True