xssh.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. # update: 2021-3-26-13
  2. """
  3. https://www.jianshu.com/p/512a5641b501
  4. # --- 上传脚本 ---
  5. sftp = s.open_sftp()
  6. sftp.put('../test.sh', '/data/test.sh')
  7. sftp.close()
  8. # --- 执行脚本并删除 ---
  9. docker exec zelu_8891 bash -c "python /home/server/projects/python-admin/zelu/libraries/protocol_l4/ssh/client.py"
  10. """
  11. import paramiko
  12. def test():
  13. host_ip = '192.168.30.13'
  14. username = 'fish'
  15. password = 'admin'
  16. client = paramiko.SSHClient()
  17. try:
  18. # --- password login ---
  19. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  20. client.connect(hostname=host_ip, port=22, username=username, password=password)
  21. # --- test ---
  22. stdin, stdout, stderr = client.exec_command('ls -all /home')
  23. # stdin, stdout, stderr = client.exec_command('ls /home/ShellScripts')
  24. print('--- --- --- ---')
  25. print(stdout.read().decode('utf-8'))
  26. except Exception as e:
  27. print(e)
  28. finally:
  29. client.close()
  30. class Client(paramiko.SSHClient):
  31. def __init__(self, ipv4='172.18.0.1', port=22, username='fish', password='admin'):
  32. super().__init__()
  33. self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  34. self.connect(hostname=ipv4, port=port, username=username, password=password)
  35. def run_script(self, script_path, host_ip, username, password, command='sh /root/1.sh && cat /home/out.txt'):
  36. """执行上传脚本"""
  37. # script_path = '/home/server/projects/user-dashboard/operation/builtin_script/linux基线检查脚本.sh'
  38. # script_path = r'D:\share\gitee\secdeer.user-dashboard-online\operation\builtin_script\linux基线检查脚本.sh'
  39. # host_ip = '47.104.160.37'
  40. # username = 'root'
  41. # password = 'Secdeer_01!'
  42. self.connect(hostname=host_ip, port=22, username=username, password=password)
  43. sftp = self.open_sftp()
  44. sftp.put(script_path, '/root/1.sh')
  45. sftp.close()
  46. # stdin, stdout, stderr = self.exec_command('ls -all /home')
  47. # stdin, stdout, stderr = self.exec_command('sh /root/1.sh')
  48. # stdin, stdout, stderr = self.exec_command('cat /home/out.txt')
  49. stdin, stdout, stderr = self.exec_command(command)
  50. output = stdout.read().decode('utf-8')
  51. print(output)
  52. print('--- --- --- ---')
  53. return output
  54. def run_command(self, command):
  55. """执行命令"""
  56. try:
  57. stdin, stdout, stderr = self.exec_command(command)
  58. output = stdout.read().decode('utf-8')
  59. return output
  60. except Exception as exception:
  61. import traceback
  62. print(f"SSHClient.run_command.exception: {exception.__class__.__name__}")
  63. print(f"SSHClient.run_command.traceback: {traceback.format_exc()}")
  64. # finally:
  65. # self.close()
  66. def run_sudo_command(self, command, password):
  67. """执行命令"""
  68. try:
  69. stdin, stdout, stderr = self.exec_command(f"echo \"{password}\" | sudo -S {command}")
  70. output = stdout.read().decode('utf-8')
  71. return output
  72. except Exception as exception:
  73. import traceback
  74. print(f"SSHClient.run_sudo_command.exception: {exception.__class__.__name__}")
  75. print(f"SSHClient.run_sudo_command.traceback: {traceback.format_exc()}")
  76. # finally:
  77. # self.close()
  78. def get_disk_utilization_rate(self, path='/'):
  79. """获取根目录磁盘所用空间占比"""
  80. try:
  81. stdin, stdout, stderr = self.exec_command("df -h")
  82. output = stdout.read().decode('utf-8')
  83. # --- get utilization_rate by '/' ---
  84. utilization_rate = str()
  85. for row in output.split('\n'):
  86. if not row:
  87. continue
  88. if row[-1] != '/':
  89. continue
  90. for val in row.split(' '):
  91. if '%' in val:
  92. utilization_rate = val
  93. break
  94. # --- transform ---
  95. if '%' in utilization_rate:
  96. utilization_rate = int(utilization_rate.strip('%'))
  97. else:
  98. utilization_rate = 0
  99. return utilization_rate
  100. except Exception as exception:
  101. import traceback
  102. print(f"SSHClient.show_root_disk.exception: {exception.__class__.__name__}")
  103. print(f"SSHClient.show_root_disk.traceback: {traceback.format_exc()}")
  104. def close(self):
  105. self.close()
  106. if __name__ == '__main__':
  107. # --- init ---
  108. # ssh = Client('192.168.30.13', 22, 'fish', 'admin')
  109. # ssh = Client('172.18.0.1', 22, 'fish', 'admin')
  110. # ssh = Client('192.168.1.45', 22, 'server', 'server')
  111. # ssh = Client('192.168.30.13', 22, 'server', 'server')
  112. ssh = Client('10.10.10.89', 22, 'nvidia', '123456')
  113. # --- test ---
  114. out = ssh.get_disk_utilization_rate()
  115. print(out)
  116. # --- test ---
  117. # out = ssh.run_command('date +%Y-%m-%d-%H-%M-%S')
  118. # date +"%Y-%m-%d %H:%M:%S"
  119. # print(out)
  120. # --- test ---
  121. # ssh.run_sudo_command('echo -e "\n#x1" >> /etc/network/interfaces', 'admin')
  122. # ssh.run_sudo_command('echo -e "\n#x1" >> /etc/network/interfaces', 'server')
  123. # ssh.run_command('echo -e "\n#x2" >> /etc/network/interfaces')
  124. # ssh.run_command('sudo echo -e "\n#x3" >> /etc/network/interfaces')
  125. # out = ssh.run_command("sudo chmod 777 /etc/network/interfaces")
  126. # out = ssh.run_command("cat /etc/network/interfaces")
  127. # print(out)
  128. # --- test ---
  129. # out = ssh.run_command("ifconfig")
  130. # for row in out.split('\n\n'):
  131. # if row[:4] != 'eth0':
  132. # continue
  133. # for one in row.split('\n'):
  134. # one = one.strip()
  135. # if one[:4] != 'inet':
  136. # continue
  137. # if one[:5] == 'inet6':
  138. # continue
  139. # one = [i for i in one.split(' ') if i]
  140. # ipv4, netmask = one[1], one[3]
  141. # print(ipv4, netmask)
  142. # --- test ---
  143. # out = ssh.run_command('ls /home/server/images')
  144. # out = ssh.run_command('rm -rf /home/server/images/*')
  145. # out = ssh.run_sudo_command('rm -rf /home/server/images/*', 'admin')
  146. # print(out)
  147. # --- test ---
  148. # out0 = ssh.run_sudo_command('chmod 777 /etc/network/interfaces', 'admin')
  149. # out1 = ssh.run_command('echo -e "\n#x2" >> /etc/network/interfaces')
  150. # out2 = ssh.run_command("cat /etc/network/interfaces")
  151. # print(out2)
  152. # --- test ---
  153. # out = c.run_command("ls -all /home")
  154. # out = c.run_command("df -h | grep 234G | awk \'{print $5}\'")
  155. # out = c.run_command("df -h | grep \"/dev/vda1\" | awk \'{print $5}\'")
  156. # out = c.run_command("df -h ")
  157. # print(out)
  158. # --- test ---
  159. # out = c.run_script(1, 2, 3, 4)
  160. # print(repr(out))
  161. # --- test ---
  162. # out = c.run_script('/home/UserFiles/hello.sh', '118.190.217.96', 'root', 'Secdeer_01!', 'sh /root/1.sh')
  163. # print(repr(out))