Advertisement
Guest User

Untitled

a guest
Feb 17th, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.43 KB | None | 0 0
  1. from cloud_utils.net_utils.sshconnection import SshConnection
  2. from cloud_utils.log_utils import red, green, blue
  3. from cloud_utils.log_utils.eulogger import Eulogger
  4. import argparse
  5. from socket import inet_aton
  6. import struct
  7. import time
  8. from threading import Thread, Lock
  9. from Queue import Queue, Empty
  10. from prettytable import PrettyTable
  11.  
  12. parser = argparse.ArgumentParser(description='Run a command on list of remote hosts',
  13. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  14. parser.add_argument('-f', '--hostfile', default=None,
  15. help='file with list of ips and/or hostnames')
  16. parser.add_argument('-i', '--ips', default=None,
  17. help='comma or space separated list of ips and/or hostnames')
  18. parser.add_argument('-p', '--password', default=None,
  19. help='Ssh password used to connect to hosts')
  20. parser.add_argument('-u', '--username', default='root',
  21. help='Ssh username used to connect to hosts. '
  22. 'Default:"root"')
  23. parser.add_argument('-c', '--command', default='echo "ALIVE"',
  24. help='file with list of ips and/or hostnames')
  25. parser.add_argument('-t', '--timeout', default=5, type=int,
  26. help='Ssh connection timeout in seconds: Default:30')
  27. parser.add_argument('--thread-count', default=20, type=int,
  28. help='Number of threads used to run commands on hosts')
  29. args = parser.parse_args()
  30. hostfile = args.hostfile
  31. password = args.password
  32. username = args.username
  33. command = args.command
  34. results = {}
  35. maxwait = .5
  36. ips = []
  37. if args.ips:
  38. ips = str(ips).replace(',', ' ')
  39. ips = ips.split()
  40. if args.hostfile:
  41. with open(hostfile) as f:
  42. ips.extend(f.readlines())
  43. if not ips:
  44. raise ValueError('No hosts provided. Use --hostfile or --ips to provide hosts to run '
  45. 'command against')
  46.  
  47. def do_ssh(q, lock, name):
  48. empty = False
  49. while not empty:
  50. ssh = None
  51. logger = None
  52. print 'Thread: {0}, in Q loop...'.format(name)
  53. try:
  54. host = q.get(timeout=maxwait)
  55. except Empty:
  56. empty = True
  57. break
  58. start = time.time()
  59. try:
  60. print 'Connecting to new host:' + str(host)
  61. logger = Eulogger(str(host))
  62. ssh = SshConnection(host=host, username=username, password=password, debug_connect=True,
  63. timeout=args.timeout, verbose=True, logger=logger)
  64. print 'host: {0} running command:{1} '.format(host, command)
  65. out = ssh.cmd(str(command), listformat=True)
  66. print 'Done with host: {0}'.format(host)
  67. elapsed = int(time.time() - start)
  68. with lock:
  69. results[host] = {'status': out.get('status'), 'output': out.get('output'),
  70. 'elapsed': elapsed}
  71. except Exception as E:
  72. elapsed = int(time.time() - start)
  73. with lock:
  74. results[host] = {'status': -1, 'output': str(E),
  75. 'elapsed': elapsed}
  76. finally:
  77. print 'Closing ssh to host: {0}'.format(host)
  78. if ssh:
  79. ssh.connection.close()
  80. try:
  81. if logger:
  82. logger.close()
  83. except:
  84. pass
  85. q.task_done()
  86. print 'Closed ssh to host: {0}'.format(host)
  87. print '{0}: Done with thread'.format(name)
  88.  
  89. iq = Queue()
  90. for ip in ips:
  91. ip = str(ip).strip().rstrip()
  92. iq.put(ip)
  93. tlock = Lock()
  94. threadcount = args.thread_count or 1
  95. for i in range(threadcount):
  96. t = Thread(target=do_ssh, args=(iq, tlock, i,))
  97. t.daemon = True
  98. t.start()
  99. print 'Threads started now waiting for join'
  100. iq.join()
  101. print 'Done with join'
  102. time.sleep(maxwait + .1)
  103. pt = PrettyTable(['HOST', 'RES', 'TIME', 'OUTPUT'])
  104. pt.align = 'l'
  105. pt.hrules = 1
  106. pt.padding_width = 0
  107. max = 80
  108. pt.max_width['OUTPUT'] = max
  109. for host in sorted(results, key=lambda ip: struct.unpack("!L", inet_aton(ip))[0]):
  110. result = results.get(host)
  111. output = ""
  112. for line in result.get('output'):
  113. output += "\n".join((line[0+i:max+i] for i in range(0, len(line), max)))
  114. status = result.get('status')
  115. if status == 0:
  116. color = green
  117. else:
  118. color = red
  119. pt.add_row([blue(host), color(result.get('status')), color(result.get('elapsed')),
  120. color(output)])
  121. print "\n{0}\n".format(pt)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement