Guest User

Untitled

a guest
Mar 29th, 2018
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.74 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. #titel, version etc.
  3. #python_version :2.6.6
  4.  
  5. import sys
  6. import threading
  7. import os
  8. import time
  9. import shlex
  10. import datetime
  11. import logging
  12. import socket
  13. import time
  14. import subprocess as sp
  15.  
  16.  
  17. # Define a function that starts to loop over every IP and creates a thread for
  18. # every device
  19. def start_threads(dict_data, devices_to_save):
  20. started_jobs = 0
  21. # Loop as long as the global counter for jobs done doesn't reach
  22. # the amount of devices meant to be save
  23. while (export_counter + failed_counter) < devices_to_save:
  24. # Loop as long as the counter for started jobs doesn't reach
  25. # the amount of devices meant to be save AND till the amount of active
  26. # jobs reaches the set threshold.
  27. # Sleep to allow threads to be opened in new process (prevent 100% CPU)
  28. time.sleep(0.001)
  29. while (started_jobs < devices_to_save) and (
  30. threading.active_count() <= parallel_jobs):
  31. # Create arguments for mkdir command via ssh
  32. mkdir_args = shlex.split("sshpass -p superpw ssh -o
  33. StrictHostKeyChecking=no myuser@192.168.1.1 mkdir -p /data/loc/
  34. tec/configs/%s/" % (data_list[started_jobs][1]))
  35. sp.call(mkdir_args)
  36. # Start a thread calling the function "trylogin" with entrys from
  37. # the data_list/dict
  38. threading.Thread(target=trylogin, args=(str
  39. (data_list[started_jobs][0]), dict_data)).start()
  40. started_jobs += 1
  41.  
  42.  
  43. # Define a function to open a SSH connection
  44. def trylogin(ipaddress, dict_data):
  45. # Use the global user and password
  46. global user, passwd
  47. # Set up a SSH channel
  48. ssh = paramiko.SSHClient()
  49. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  50. # Try to open a connection with the data provided
  51. try:
  52. ssh.connect(ipaddress, username=user, password=passwd)
  53. logging.info("[+%s] Connected %s" % (threading.currentThread(),
  54. get_name_by_ip(ipaddress, dict_data)))
  55. # Catch exceptions
  56. except paramiko.ssh_exception.SSHException as e:
  57. export_failed(ipaddress, get_name_by_ip(ipaddress, dict_data))
  58. logging.info("[-%s] Failed %s %s" % (threading.currentThread(), e,
  59. get_name_by_ip(ipaddress, dict_data)))
  60. return
  61. except socket.timeout as e:
  62. export_failed(ipaddress, get_name_by_ip(ipaddress, dict_data))
  63. logging.info("[-%s] Failed %s %s" % (threading.currentThread(), e,
  64. get_name_by_ip(ipaddress, dict_data)))
  65. return
  66. # Execute the "config export" command on the connected device
  67. stdin, stdout, stderr = ssh.exec_command("config export")
  68. # Wait for the "config export" to finish
  69. exit_status = stdout.channel.recv_exit_status()
  70. # Transfer the config to the backup server
  71. stdin, stdout, stderr = ssh.exec_command("sshpass -p superpw scp
  72. /tmp/upload/config.tar myuser@192.168.1.1:/data/loc/tec/
  73. configs/%s/" % (get_name_by_ip(ipaddress, dict_data)))
  74. exit_status = stdout.channel.recv_exit_status()
  75. # Close the SSH connection
  76. ssh.close()
  77. export_done()
  78. logging.info("[+%s] %s %s" % (threading.currentThread(), export_counter,
  79. get_name_by_ip(ipaddress, dict_data)))
  80.  
  81.  
  82. # Define a function to look up the device name
  83. def get_name_by_ip(ipaddress, dict_data):
  84. name = dict_data[ipaddress]
  85. return name
  86.  
  87.  
  88. # Define a function to count the created config files
  89. def export_done():
  90. # Make the variable global
  91. global export_counter
  92. export_counter += 1
  93.  
  94.  
  95. # Define a function to count failed export attempts
  96. def export_failed(ipaddress, device_name):
  97. # Make the variable global
  98. global failed_counter
  99. global failed_data
  100. failed_data.append((ipaddress, device_name))
  101. failed_counter += 1
  102.  
  103.  
  104. # Define a function that starts to loop over every IP from failed connections
  105. def start_failed_threads(dict_data, devices_to_save):
  106. started_jobs = 0
  107. data_list_failed = []
  108. # Make new data list for failed IPs and device names
  109. for key, value in dict_data.iteritems():
  110. data_list_failed.append((key, value))
  111. # Loop as long as the combined counters don't reacht the amount of devices
  112. # meant to be saved
  113. while (export_counter + failed_counter) < devices_to_save:
  114. # Loop as long as the counter for started jobs doesn't reach the amount
  115. # of devices meant to be save AND till the amount of active jobs
  116. # reaches the set threshold.
  117. # Sleep to allow threads to be opened in new process
  118. time.sleep(0.001)
  119. while (started_jobs < devices_to_save) and (
  120. threading.active_count() <= parallel_jobs):
  121. # Start a thread calling the function "trylogin" with data from
  122. # failed connections
  123. threading.Thread(target=trylogin, args=(str
  124. (data_list_failed[started_jobs][0]), dict_data)).start()
  125. # Count up the started jobs
  126. started_jobs += 1
  127.  
  128.  
  129. if __name__ == "__main__":
  130. socket.setdefaulttimeout(2)
  131. now = datetime.datetime.now()
  132. user = "root"
  133. passwd = "secpw"
  134. export_counter = 0
  135. failed_counter = 0
  136. failed_data = []
  137. parallel_jobs = 10
  138. LOG_FILENAME = "/data/Admin/logs/%s.txt" % (now.strftime("%Y-%m-%d"))
  139. logging.basicConfig(format="%(asctime)s %(message)s",
  140. filename=LOG_FILENAME, level=logging.INFO)
  141. with open("/data/Admin/data/IP_Hostname_.txt") as ips_file:
  142. # Empty list for hosts
  143. data_list = []
  144. # Read lines from IP_Hostname_.txt format is IP;Hostname;
  145. content = ips_file.readlines()
  146. # Iterate over all lines, except header
  147. for line in content[1:]:
  148. # Split line at ";" and get the first entry (device_ip)
  149. device_ip = line.split(";")[0]
  150. device_name = (line.split(";")[1]).replace("n", "")
  151. # Append a tuple with host IP and name to the data_list
  152. data_list.append((device_ip, device_name))
  153. # Set the amount of devices that are meant to be saved
  154. devices_to_save = len(data_list)
  155. # Create dictionary
  156. dict_data = dict(data_list)
  157. # Start threading
  158. start_threads(dict_data, devices_to_save)
  159. helper_counter = export_counter
  160. if failed_data:
  161. # Attempt to save all failed devices, do that three times and wait 10s
  162. # between trys
  163. for i in range(3):
  164. time.sleep(10)
  165. dict_failed_data = dict(failed_data)
  166. failed_data = []
  167. export_counter = 0
  168. failed_counter = 0
  169. start_failed_threads(dict_failed_data, len(dict_failed_data))
  170. for element in failed_data:
  171. logging.warning("###failed connections" + str(element))
  172. time.sleep(1)
  173. logging.info("###devices saved " + str(helper_counter))
  174. logging.info("###time needed " + str(datetime.datetime.now() - now))
Add Comment
Please, Sign In to add comment