Guest User

Untitled

a guest
Dec 29th, 2017
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.86 KB | None | 0 0
  1. def main(db_server):
  2. try:
  3. ip = db_server
  4. username = r''
  5. password = ''
  6. server = WindowsMachine(ip, username, password)
  7. print("connection established")
  8. status_check = server.run_remote(r'python <your python script address>', async=False, output=True)
  9.  
  10. print(status_check)
  11. if "running" in status_check:
  12. return "Proceed"
  13. else:
  14. return "Stop"
  15. except Exception:
  16. print (sys.exc_info())
  17. return "Stop"
  18.  
  19.  
  20. def create_file(filename, file_text):
  21. f = open(filename, "w")
  22. f.write(file_text)
  23. f.close()
  24. REMOTE_PATH = 'C://'
  25.  
  26. class WindowsMachine:
  27. def __init__(self, ip, username, password, remote_path=REMOTE_PATH):
  28. self.ip = ip
  29. self.username = username
  30. self.password = password
  31. self.remote_path = remote_path
  32. try:
  33. print ("Establishing connection to %s" %self.ip)
  34. self.connection = wmi.WMI(self.ip, user=self.username, password=self.password)
  35. print ("Connection established")
  36. except wmi.x_wmi:
  37. print ("Could not connect to machine")
  38. raise
  39.  
  40. def run_remote(self, cmd, async=False, minimized=True, output=False):
  41. """
  42. this function runs cmd on remote machine, using wmi. the function create a .bat file,
  43. copies it to the remote machine, and runs the .bat file
  44. inputs: cmd - command to run
  45. async - False, waits for command to finish, True, return immidiatly
  46. mimimized - window state
  47. output - True, returns the command's output
  48. output: return value of the command
  49. output of the command if true
  50. """
  51. output_data = None
  52. pwd = os.getcwd()
  53.  
  54. bat_local_path = os.path.join(pwd, 'output.bat')
  55. bat_remote_path = os.path.join(self.remote_path, 'output.bat')
  56. script_local_path = os.path.join(self.pwd,'filename.py')
  57. script_remote_path = os.path.join(self.remote_path,'filename.py')
  58.  
  59.  
  60.  
  61. output_remote_path = os.path.join(self.remote_path, 'output.out')
  62. output_local_path = os.path.join(pwd, 'output.out')
  63.  
  64. text = cmd + " > " + output_remote_path
  65. create_file(bat_local_path, text)
  66. self.net_copy(bat_local_path, self.remote_path)
  67. batcmd = bat_remote_path
  68.  
  69. SW_SHOWMINIMIZED = 0
  70. if not minimized:
  71. SW_SHOWMINIMIZED = 1
  72. print ("Executing %s" %cmd)
  73. startup = self.connection.Win32_ProcessStartup.new (ShowWindow=SW_SHOWMINIMIZED)
  74. process_id, return_value = self.connection.Win32_Process.Create (CommandLine=batcmd, ProcessStartupInformation=startup)
  75. if async:
  76. watcher = self.connection.watch_for (
  77. notification_type="Deletion",
  78. wmi_class="Win32_Process",
  79. delay_secs=1,
  80. )
  81. watcher ()
  82.  
  83. if output and not async:
  84. print ('copying back ' + output_remote_path)
  85. self.net_copy_back(output_remote_path, output_local_path)
  86. output_data = open(output_local_path, 'r')
  87. output_data = "".join(output_data.readlines())
  88. self.net_delete(output_remote_path)
  89. self.net_delete(bat_remote_path)
  90. self.net_delete(script_remote_path)
  91. return return_value, output_data
  92.  
  93. def net_copy(self, source, dest_dir, move=False):
  94. """ Copies files or directories to a remote computer. """
  95. print ("Start copying files to " + self.ip)
  96. if self.username == '':
  97. if not os.path.exists(dest_dir):
  98. os.makedirs(dest_dir)
  99. else:
  100. # Create a directory anyway if file exists so as to raise an error.
  101. if not os.path.isdir(dest_dir):
  102. os.makedirs(dest_dir)
  103. shutil.copy(source, dest_dir)
  104.  
  105. else:
  106. self._wnet_connect()
  107.  
  108. dest_dir = self._covert_unc(dest_dir)
  109.  
  110. # Pad a backslash to the destination directory if not provided.
  111. if not dest_dir[len(dest_dir) - 1] == '\':
  112. dest_dir = ''.join([dest_dir, '\'])
  113.  
  114. # Create the destination dir if its not there.
  115. if not os.path.exists(dest_dir):
  116. os.makedirs(dest_dir)
  117. else:
  118. # Create a directory anyway if file exists so as to raise an error.
  119. if not os.path.isdir(dest_dir):
  120. os.makedirs(dest_dir)
  121.  
  122. if move:
  123. shutil.move(source, dest_dir)
  124. else:
  125. shutil.copy(source, dest_dir)
  126.  
  127. def net_copy_back(self, source_file, dest_file):
  128. """ Copies files or directories to a remote computer. """
  129. print ("Start copying files " + source_file + " back from " + self.ip)
  130. if self.username == '':
  131. shutil.copy(source_file, dest_file)
  132. else:
  133. self._wnet_connect()
  134. source_unc = self._covert_unc(source_file)
  135. shutil.copyfile(source_unc, dest_file)
  136.  
  137. def _wnet_connect(self):
  138. unc = ''.join(['\\', self.ip])
  139. try:
  140. win32wnet.WNetAddConnection2(0, None, unc, None, self.username, self.password)
  141. except (Exception, err):
  142. if isinstance(err, win32wnet.error):
  143. # Disconnect previous connections if detected, and reconnect.
  144. if err[0] == 1219:
  145. win32wnet.WNetCancelConnection2(unc, 0, 0)
  146. return self._wnet_connect(self)
  147. raise err
  148.  
  149. def _covert_unc(self, path):
  150. """ Convert a file path on a host to a UNC path."""
  151. return ''.join(['\\', self.ip, '\', path.replace(':', '$')])
  152.  
  153. def copy_folder(self, local_source_folder, remote_dest_folder):
  154. files_to_copy = os.listdir(local_source_folder)
  155. for file in files_to_copy:
  156. file_path = os.path.join(local_source_folder, file)
  157. print ("Copying " + file)
  158. try:
  159. self.net_copy(file_path, remote_dest_folder)
  160. except WindowsError:
  161. print ('could not connect to ', self.ip)
  162. except IOError:
  163. print ('One of the files is being used on ', self.ip, ', skipping the copy procedure')
  164.  
  165. def net_delete(self, path):
  166. """ Deletes files or directories on a remote computer. """
  167. if self.username == '':
  168. os.remove(path)
  169.  
  170. else:
  171. self._wnet_connect()
  172.  
  173. path = self._covert_unc(path)
  174. if os.path.exists(path):
  175. # Delete directory tree if object is a directory.
  176. if os.path.isfile(path):
  177. os.remove(path)
  178. else:
  179. shutil.rmtree(path)
  180. else:
  181. # Remove anyway if non-existent so as to raise an error.
  182. os.remove(path)
Add Comment
Please, Sign In to add comment