Python 自动化运维脚本示例(并行发送sh命令)

前端之家收集整理的这篇文章主要介绍了Python 自动化运维脚本示例(并行发送sh命令)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
感兴趣Python 自动化运维脚本示例的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
  1. # 编程之家 (jb51.cc)
  2. #!/usr/bin/python
  3. # -*- coding: UTF-8 -*-
  4. import paramiko
  5. import sys
  6. import threading
  7. #Copy local file to remote server.
  8. def sshclient_scp(hostname,port,username,password,local_path,remote_path):
  9. t = paramiko.Transport((hostname,port))
  10. t.connect(username=username,password=password) # 登录远程服务器
  11. sftp = paramiko.SFTPClient.from_transport(t) # sftp传输协议
  12. sftp.put(local_path,remote_path)
  13. t.close()
  14. def sshclient_scp_get(hostname,remote_path,local_path):
  15. t = paramiko.Transport((hostname,password=password) # 登录远程服务器
  16. sftp = paramiko.SFTPClient.from_transport(t) # sftp传输协议
  17. sftp.get(remote_path,local_path)
  18. t.close()
  19. def sshclient_execmd(hostname,execmd):
  20. paramiko.util.log_to_file("paramiko.log")
  21. s = paramiko.SSHClient()
  22. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  23. s.connect(hostname=hostname,port=port,username=username,password=password)
  24. stdin,stdout,stderr = s.exec_command(execmd)
  25. stdin.write("Y") # Generally speaking,the first connection,need a simple interaction.
  26. line=stdout.read()
  27. s.close()
  28. print (hostname+":")
  29. print line
  30. try:
  31. file_name = sys.argv[1]
  32. cmd= sys.argv[2]
  33. except IndexError:
  34. print 'Wrong params!'
  35. print 'Usage :'
  36. print ' batch.py "$OS_LIST_FILE" "$BATCH_EXECUTE_CMD"'
  37. print 'cat oslist.txt:'
  38. print '192.168.0.1,22,oracle,passwd1'
  39. print '192.168.0.2,passwd1'
  40. print '192.168.0.3,24,passwd1'
  41. print 'Format is :'
  42. print 'IPADDR,SSHPORT,USERNAME,PASSWORD'
  43. print 'Examples of usage:'
  44. print './batch.py "/root/workspace/oslist.txt" "df -h"'
  45. sys.exit()
  46. #file_name = sys.argv[1]
  47. #cmd= sys.argv[2]
  48. #maintenance_osinfo
  49. with open(file_name) as file_object:
  50. for line in file_object:
  51. splits_str = line.rstrip().split(',')
  52. a=threading.Thread(target=sshclient_execmd,args=(splits_str[0],int(splits_str[1]),splits_str[2],splits_str[3],cmd))
  53. a.start()
  54. #print sshclient_execmd(splits_str[0],cmd)
  55. # print sshclient_scp(splits_str[0],file_name,splits_str[4]+file_name)
  56. # End 5.1.2笔记-jb51.cc
 

猜你在找的Python相关文章