WHCSRL 技术网

python学习(paramiko远程操作主机)

  1. import time,paramiko,os
  2. def run_cmd(ssh_client,cmd):
  3. print("执行命令: " + cmd)
  4. stdin, stdout, stderr = ssh_client.exec_command(cmd)
  5. error_msg = stderr.read().decode('utf8')
  6. result = stdout.read().decode('utf8')
  7. if not error_msg:
  8. print("run_cmd 命令执行结果: " + result)
  9. else:
  10. print("run_cmd error: " + error_msg)
  11. return result
  12. def clent(host,username,password,port):
  13. ssh_client = paramiko.SSHClient()
  14. ssh_client.load_system_host_keys()
  15. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  16. ssh_client.connect(host, port, username=username, password=password, timeout=5)
  17. cmd_pid = "ps -ef | grep " + app_name + " | grep -v grep | awk '{print $2}'"
  18. pid = run_cmd(ssh_client, cmd_pid)
  19. if not pid:
  20. print("进程号不存在!")
  21. else:
  22. print(pid)
  23. if __name__ == "__main__":
  24. date = time.strftime('%%Y%%m%%d%%H%%M%%S', time.localtime())
  25. dir = '/home/backup/'
  26. app_name = "webapp-test"
  27. app_home = "/app/application/"
  28. cmd = "tar -czPf %%s%%s_%%s.tar.gz %%s%%s.jar" %% (dir, app_name, date, app_home, app_name)
  29. host = '' #远程的主机
  30. port = 22 #远程的ssh端口
  31. username = '' #远程的用户名
  32. password = '' #远程的用户密码
  33. clent(host,username,password,port)
  34. '''
  35. 远程机器为不同密码或不同用户端口可以使用以下方式:
  36. 密码文件格式ip,端口,用户,密码
  37. 192.168.137.100,22,root,123456
  38. 192.168.137.101,22,root,123456
  39. 存放密码文件本地路径
  40. host_txt = r'E:py_projecthost_site.txt'
  41. 遍历登录账户密码文件
  42. for i in open(host_txt, 'r').readlines():
  43. r = i.strip().split(',')
  44. host, port, username, password = r
  45. clent(host,username,password,port)
  46. '''

推荐阅读