How to use FindByXPATH method in websmith

Best Python code snippet using websmith_python

main.py

Source:main.py Github

copy

Full Screen

1import pickle, re, os, datetime, colorama2from selenium import webdriver3from time import sleep, clock, gmtime, strftime4#Setup global vars5global ips6ips = []7global btcAddr8btcAddr = []9global btcPass10btcPass = []11########12# To-Do:13########14class Links:15 #Setup links to the website16 base = 'https://legacy.hackerexperience.com/'17 log = base + 'log'18 index = base + 'index'19 home = base + 'index.php'20 ddos = base + 'list?action=ddos'21 software = base + 'software'22 internet = base + 'internet'23 harddisk = base + 'software?page=external'24 hardware = base + 'hardware'25 processes = base + 'processes'26 download = harddisk + "&action=download&id="27 install = software + '?action=install&id='28 uninstall = software + '?action=uninstall&id='29 delete = software + '?action=del&id='30 hide = software + '?action=hide&id='31 information = software + '?id='32 internetWithIp = internet + '?ip='33 internetHack = internet + '?action=hack'34 internetBruteforce = internet + '?action=hack&method=bf'35 internetLogin = internet + '?action=login'36 internetLog = internet + '?view=logs'37 internetSoftware = internet + '?view=software'38 internetLogout = internet + '?view=logout'39 internetInstall = internetSoftware + '&cmd=install&id='40 internetUninstall = internetSoftware + '&cmd=uninstall&id='41 internetInformation = internetSoftware + '&id='42 internetUpload = internetSoftware + '&cmd=up&id='43 internetHide = internetSoftware + '&cmd=hide&id='44#Setup Error strings45class Error:46 crackerNotGoodEnough = "Error! Access denied: your cracker is not good enough."47 noCracker = "Error! You do not have the needed software to perform this action."48 login = "Error! This IP is already on your hacked database."49 invalidIp = "Error! Invalid IP address."50 notHacked = "Error! This IP is not on your Hacked Database."51 notUploaded = "Error! You do not have enough disk space to download this software."52 processNotFound = "Error! Process not found."53 fileHidden = "Error! This software already exists on your root folder."54 identicalLog = "Error! Identical logs."55 alreadyClearingLog = "Error! There already is a log edit in progress. Delete or complete it before."56#Setup Error paths57class ErrorPath:58 file = "/html/body/div[5]/div[3]/div/div/div[1]/strong"59 ddos = "/html/body/div[5]/div[3]/div/div/div/div[2]/div/div[1]/div/div[2]/strong"60 internetLog = "/html/body/div[5]/div[3]/div/div[1]/strong"61 notUploaded = "/html/body/div[5]/div[3]/div/div[1]/div[2]/strong"62 login = "/html/body/div[5]/div[3]/div/div[1]/div[2]/strong"63 log = '//*[@id="content"]/div[3]/div/div/div[1]/strong'64 process = '//*[@id="content"]/div[3]/div/div[1]/strong'65def Main():66 MakeLog()67 ImportSettings()68 StartBrowser()69 LogIn()70 Print(GetInfectedIps())71def StartBrowser():72 Print("# Starting Browser #")73 global browser74 chromeOptions = webdriver.chrome.options.Options()75 chromeOptions.add_argument('--log-level=3')76 browser = webdriver.Chrome(chrome_options=chromeOptions)77 browser.set_window_size(970, 1045)78 browser.set_window_position(0, 0)79 browser.get(Links.base)80 #Removes the devtools message81 colorama.init()82 print("\u001b[1A",end="")83 print("\033[K",end="")84 print("\u001b[1A",end="")85 Print("")86def LogIn():87 Print("# Logging In #")88 if LoadCookies() == False:89 SaveCookies()90 browser.get(Links.home)91 Print("")92def ImportSettings():93 Print("# Importing Settings #")94 global debug, signature, password, userName, firefox, breaker, cracker95 #Import settings if it exists96 try: import settings97 except NameError: pass98 #Set vars from settings99 try: debug = settings.debug100 except NameError: debug = False101 try: signature = settings.signature102 except NameError: signature = ""103 try: password = settings.password104 except NameError: password = ""105 try: userName = settings.userName106 except NameError: userName = ""107 try: firefox = settings.firefox108 except NameError: firefox = False109 try: breaker = settings.breaker110 except NameError: breaker = "None"111 try: cracker = settings.cracker112 except NameError: cracker = "None"113 Print("")114def LoadCookies():115 #Trys to log in using cookies.116 #It returns True if log in was successfull and False if it fails to do so117 PrintLog("Loading cookies")118 try:119 cookies = pickle.load(open("cookies.pkl", "rb"))120 for cookie in cookies:121 browser.add_cookie(cookie)122 except:123 PrintLog("Error loading cookies")124 return False125 else:126 PrintLog("Loaded cookies correctly")127 browser.get(Links.hardware)128 sleep(5)129 if browser.current_url == Links.index:130 Print("Couldn't log in with cookies, please log in manually")131 return False132 else:133 Print("Successfully logged in with cookies")134 return True135def SaveCookies():136 #Log in137 loginButton = FindByXpath('/html/body/div[2]/div[2]/div/div/div/ul/li[1]/a')138 userNameField = FindByXpath('//*[@id="login-username"]')139 userPasswordField = FindByXpath('//*[@id="password"]')140 loginButton.click()141 userNameField.send_keys(userName)142 userPasswordField.send_keys(password)143 #Wait for user to login144 WaitForLoad(Links.home, reload = False, errorCheck = False)145 Print("Saving cookies in 5 seconds")146 sleep(5)147 pickle.dump(browser.get_cookies() , open("cookies.pkl","wb"))148 Print("Saved cookies")149def MakeLog():150 #Make a dir called logs if it doesn't exist151 if not os.path.exists("logs"):152 os.makedirs("logs")153 #Make log file154 global logName155 logName = "logs\\" + datetime.datetime.now().strftime('%Y-%m-%d_%H;%M.log')156def PrintLog(inputString):157 #Write to log and only print to terminal if script is in debug mode158 inputString = str(RoundTime(datetime.datetime.now().time())) + " " + str(inputString)159 if debug:160 print(inputString)161 file = open(logName,"a")162 file.write(str(inputString) + "\n")163 file.close164def Print(inputString):165 #Write to log and print to terminal166 inputString = str(RoundTime(datetime.datetime.now().time())) + " " + str(inputString)167 print(inputString)168 file = open(logName,"a")169 file.write(str(inputString) + "\n")170 file.close171def RoundTime(currentTime, secs = 0):172 #Roundtime to nearest second173 newTime = datetime.datetime(100, 1, 1, currentTime.hour, currentTime.minute, currentTime.second)174 returnTime = newTime + datetime.timedelta(seconds=secs)175 return returnTime.time()176def WaitForLoad(link, reload = True, errorCheck = True, errorPath = None):177 def WaitForLoadLoop(errorCheck,errorPath):178 #Loop used in WaitForLoad179 if reload:180 browser.refresh()181 RemoveElement('//*[@id="he2"]')182 RemoveElement('//*[@id="gritter-notice-wrapper"]')183 sleep(1)184 ErrorCheck(ErrorPath.process)185 if errorText[1] == Error.processNotFound:186 PrintLog("Process not found, getting link")187 browser.get(link)188 if WaitForLoadErrorCheck(errorCheck, errorPath):189 return False190 def WaitForLoadErrorCheck(errorCheck, errorPath = None):191 #Function used in WaitForLoad, check if an error is present192 if errorPath != None:193 if errorCheck:194 return ErrorCheck(errorPath)195 else:196 ErrorCheck(errorPath)197 def ErrorCheck(errorPath = None):198 #Get string from the errorPath199 global errorText200 try:201 error = FindByXpath(errorPath, False)202 except:203 errorText = ["","None"]204 return False205 else:206 error = FindByXpath(errorPath.replace("/strong", ""))207 errorText = error.text.replace("×","x").split("\n")208 try:209 if errorText[0] == "x":210 PrintLog(errorText)211 errorText.append(errorText[-1])212 except:213 PrintLog("ERRORMAYBE Return False 2")214 errorText = ["","None"]215 return False216 else:217 return True218 #Check if an error has appeared219 if WaitForLoadErrorCheck(errorCheck, errorPath):220 return False221 #Wait for a website to load222 Print ("Waiting for " + str(link) + " to load")223 if type(link) == type(''):224 while browser.current_url != link:225 if WaitForLoadLoop(errorCheck,errorPath):226 return False227 elif type(link) == type([]):228 while browser.current_url not in link:229 if WaitForLoadLoop(errorCheck,errorPath):230 return False231 else:232 Print("ERROR IN WAITFORLOAD")233 return True234def FindByXpath(xpath, shouldWait = False):235 #Find and return element by xpath236 if shouldWait == False:237 return browser.find_element_by_xpath(xpath)238 else:239 counter = 0240 while True:241 try:242 return browser.find_element_by_xpath(xpath)243 except:244 if counter > 10:245 Print("Stuck on FindByXpath: " + xpath)246 counter+=1247 sleep(1)248def RemoveElement(xpath):249 try:250 element = FindByXpath(xpath)251 except:252 #Couldn't remove element253 pass254 else:255 try:256 browser.execute_script("""257 var element = arguments[0];258 element.parentNode.removeChild(element);259 """, element)260 except:261 #Couldn't remove element262 pass263def GetElementLen(xpath1,xpath2, shouldWait = False):264 i = 1265 while i < 1000:266 try:267 FindByXpath(xpath1 + str(i) + xpath2, shouldWait = shouldWait)268 except:269 return i-1270 else:271 i+=1272 Print("ERRORMAYBE Something went wrong in GetElementLen")273def YourIp():274 #Get your ip275 yourIp = FindByXpath('//*[@id="content-header"]/div/div[1]/span', shouldWait = True)276 yourIp = yourIp.text277 return yourIp278def WriteToFiles(ip, minSoftwareVersion, i):279 #WriteToFiles is used for logging280 try:281 float(versions[i])282 except:283 return False284 else:285 if minSoftwareVersion <= float(versions[i]):286 with open("software" + str(minSoftwareVersion) + ".txt", "a") as myfile:287 myfile.write(ip + ": " + softwares[i] + " " + versions[i] + " " + sizes[i] + "\n")288 return True289def GetIpsFromLog(logLines):290 #Get ips from the log291 for logLine in logLines:292 global ips293 foundIpList = re.findall( r'[0-9]+(?:\.[0-9]+){3}', logLine)294 for foundIp in foundIpList:295 if foundIp in ips:296 continue297 elif foundIp == YourIp():298 continue299 else:300 ips.append(foundIp)301def GetBTCFromLog(logLines):302 global btcAddr303 global btcPass304 tempBtcAddr = []305 tempBtcPass = []306 for logLine in logLines:307 try:308 tempBtcAddr.append(re.search("[a-zA-Z0-9]{34} ", logLine).group())309 tempBtcPass.append(re.search("[a-zA-Z0-9]{64}", logLine).group())310 except:311 pass312 if len(tempBtcAddr) == len(tempBtcPass):313 for i in range(0,len(tempBtcAddr)):314 if tempBtcAddr[-1] not in btcAddr:315 btcAddr.append(tempBtcAddr.pop())316 btcPass.append(tempBtcPass.pop())317def GetInfectedIps():318 browser.get(Links.ddos)319 ipsInText = FindByXpath('//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[2]/div/div[2]').text320 foundIpList = re.findall( r'[0-9]+(?:\.[0-9]+){3}', ipsInText)321 ips = []322 for foundIp in foundIpList:323 ips.append(foundIp)324 return ips325def ClearLog():326 #Clears user log327 browser.get(Links.log)328 logField = FindByXpath('//*[@id="content"]/div[3]/div/div/div/div[2]/div[2]/form/textarea', shouldWait = True)329 editLogButton = FindByXpath('//*[@id="content"]/div[3]/div/div/div/div[2]/div[2]/form/input[2]', shouldWait = True)330 logField.clear()331 editLogButton.click()332 #ErrorHandling stage (identical logs and a clear log in progress)333 while WaitForLoad(Links.log, errorPath = ErrorPath.log) == False:334 #Identical logs335 if errorText[1] == Error.identicalLog:336 Print("Your log had already been cleared")337 return False338 #AlreadyClearingLog339 if errorText[1] == Error.alreadyClearingLog:340 Print("There is already a clear log in progress")341 browser.get(Links.processes)342 proccesCount = GetElementLen('//*[@id="content"]/div[3]/div/div/div[2]/ul/li[',']/div[1]')343 #Loop through all processes344 for i in range(0+1,proccesCount+1):345 element = FindByXpath('//*[@id="content"]/div[3]/div/div/div[2]/ul/li[' + str(i) + ']/div[1]')346 if element.text == "Edit log at localhost":347 completeButton = FindByXpath('//*[@id="content"]/div[3]/div/div/div[2]/ul/li[' + str(i) + ']/div[3]/div[2]/form/input[2]')348 completeButton.click()349 break350 else:351 PrintLog("ERRORMAYBE An error has accored in ClearLog during the errorhandling stage")352 return False353 break354 sleep(1)355 Print("Your log has been cleared")356 return True357def GetHDD(MB = True, internet = True):358 #Get HHD returns float or int359 if internet:360 browser.get(Links.internetSoftware)361 fullHDD = FindByXpath("""/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div[2]/div/div[2]/span/font[2]""", shouldWait = True).text362 usedHDD = FindByXpath("""/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div[2]/div/div[2]/span/font[1]""", shouldWait = True).text363 else:364 browser.get(Links.software)365 fullHDD = FindByXpath('//*[@id="softwarebar"]/div/span/font[2]', shouldWait = True).text366 usedHDD = FindByXpath('//*[@id="softwarebar"]/div/span/font[1]', shouldWait = True).text367 if "GB" in fullHDD:368 fullHDD = float(fullHDD.replace(" GB", ""))369 fullHDD *= 1000370 else:371 fullHDD = float(fullHDD.replace(" MB", ""))372 if "GB" in usedHDD:373 usedHDD = float(usedHDD.replace(" GB", ""))374 usedHDD *= 1000375 else:376 usedHDD = float(usedHDD.replace(" MB", ""))377 if MB:378 return int(fullHDD - usedHDD)379 else:380 return (fullHDD - usedHDD)/1000381def GetInternetSpeed(Mbit = True, internet = True):382 #Get Internetspeed returns int or float383 if internet:384 browser.get(Links.internetSoftware)385 internetSpeed = FindByXpath("""/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div[2]/div/div[1]/span/strong""", shouldWait = True).text386 else:387 browser.get(Links.hardware)388 internetSpeed = FindByXpath('//*[@id="content"]/div[3]/div/div/div/div[2]/ul/li[4]/div[2]', shouldWait = True).text.replace("\n"," ")389 if "Gbit" in internetSpeed:390 internetSpeed = int(internetSpeed.replace(" Gbit", ""))391 internetSpeed *= 1000392 else:393 internetSpeed = int(internetSpeed.replace(" Mbit", ""))394 if Mbit:395 return internetSpeed396 else:397 return internetSpeed/1000398def GetYourHarddisk():399 #Get all important data from your harddisk400 browser.get(Links.harddisk)401 global harddiskIds402 global harddiskSoftwares403 global harddiskVersions404 global harddiskSizes405 harddiskIds = ["None"]406 harddiskSoftwares = ["None"]407 harddiskVersions = ["None"]408 harddiskSizes = ["None"]409 Print("Getting harddisk software")410 baseXpath = "/html/body/div[5]/div[3]/div/div/div/div[2]/div[1]/table/tbody/"411 softwareCount = GetElementLen(baseXpath + 'tr[',']')412 for i in range(1,softwareCount+1):413 try:414 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[5]/a[1]")415 except:416 continue417 id = info.get_attribute('href').replace(Links.information, "")418 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[2]")419 software = info.text420 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[3]")421 version = info.text422 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[4]")423 size = info.text424 harddiskSizes.insert(i, size)425 harddiskVersions.insert(i, version)426 harddiskSoftwares.insert(i, software)427 harddiskIds.insert(i, id)428def GetYourSoftware():429 #Get all important data from your software430 browser.get(Links.software)431 global yourIds432 global yourSoftwares433 global yourVersions434 global yourSizes435 yourIds = ["None"]436 yourSoftwares = ["None"]437 yourVersions = ["None"]438 yourSizes = ["None"]439 Print("Getting your software")440 baseXpath = "/html/body/div[5]/div[3]/div/div/div/div[2]/div/table/tbody/"441 softwareCount = GetElementLen(baseXpath + 'tr[',']')442 for i in range(1,softwareCount+1):443 try:444 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[5]/a[1]")445 except:446 continue447 id = info.get_attribute('href').replace(Links.install, "")448 id = id.replace(Links.uninstall, "")449 id = id.replace(Links.delete,"")450 id = id.replace(Links.hide,"")451 id = id.replace(Links.information,"")452 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[2]")453 software = info.text454 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[3]")455 version = info.text456 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[4]")457 size = info.text458 yourSizes.insert(i, size)459 yourVersions.insert(i, version)460 yourSoftwares.insert(i, software)461 yourIds.insert(i, id)462def GetInternetSoftware(ip = "No ip was given"):463 #Get all important data from the connected machines software464 browser.get(Links.internetSoftware)465 global ids466 global softwares467 global versions468 global sizes469 ids = ["None"]470 softwares = ["None"]471 versions = ["None"]472 sizes = ["None"]473 Print("Getting software information from " + ip)474 baseXpath = "/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div[1]/table/tbody/"475 softwareCount = GetElementLen(baseXpath + 'tr[',']')476 for i in range(1,softwareCount+1):477 try:478 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[5]/a[1]")479 except:480 continue481 id = info.get_attribute('href').replace(Links.internetInstall, "")482 id = id.replace(Links.internetUninstall, "")483 id = id.replace(Links.internetHide,"")484 id = id.replace(Links.internetInformation,"")485 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[2]")486 software = info.text487 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[3]")488 version = info.text489 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[4]")490 size = info.text491 sizes.insert(i, size)492 versions.insert(i, version)493 softwares.insert(i, software)494 ids.insert(i, id)495 WriteToFiles(ip, 2, i)496 for j in range(1,10):497 WriteToFiles(ip, j*10, i)498def Install(software):499 #Install software locally500 Print("Installing " + software)501 GetYourSoftware()502 try:503 i = yourSoftwares.index(software)504 Print(software + " is not in your softwares")505 except:506 return False507 browser.get(Links.install + yourIds[i])508 WaitForLoad(Links.software)509 Print(software + " installed")510 return True511def Download(software):512 #Download files from harddisk513 Print("Downloading " + software)514 GetYourHarddisk()515 try:516 i = harddiskSoftwares.index(software)517 except:518 Print(software + " is not in harddisk")519 return False520 browser.get(Links.download + harddiskIds[i])521 #WaitForLoad(Links.software)522 if WaitForLoad(Links.software, errorPath=ErrorPath.file) == False:523 if Error.fileHidden == errorText[1]:524 Print(software + " is already on machine")525 return False526 Print(software + " downloaded")527 return True528def InternetInstall(software,ip=""):529 #Install file on internet machine530 Print("Installing " + software + " on " + ip)531 GetInternetSoftware(ip)532 try:533 i = softwares.index(software)534 except:535 return False536 browser.get(Links.internetInstall + ids[i])537 WaitForLoad([Links.internet, Links.internetSoftware])538 Print(software + " installed" + " on " + ip)539 InternetClearLog(ip)540 return True541def InternetHide(software, ip=""):542 #Hide file on internet machine543 Print("Hiding " + software + " on " + ip)544 GetInternetSoftware(ip)545 try:546 i = softwares.index(software)547 except:548 return False549 browser.get(Links.internetHide + ids[i])550 WaitForLoad([Links.internet, Links.internetSoftware])551 Print(software + " hid" + " on " + ip)552 InternetClearLog(ip)553 return True554def InternetUpload(software, ip=""):555 #Upload file to internet machine556 Print("Uploading " + software + " on " + ip)557 GetYourSoftware()558 try:559 i = yourSoftwares.index(software)560 if yourIds[i] == "None":561 0/0562 except:563 return "Download"564 browser.get(Links.internetUpload + yourIds[i])565 WaitForLoad([Links.internet, Links.internetSoftware], errorPath = ErrorPath.notUploaded)566 if errorText[1] == Error.notUploaded:567 Print(software + " couldn't be uploaded, not enough space on " + ip + "??")568 return False569 Print(software + " uploaded" + " on " + ip)570 InternetClearLog(ip)571 return True572def InternetClearLog(ip = "", getIps = False, getBTCs = False):573 #Clear the log on the connected machine574 Print("Clearing log on " + ip)575 browser.get(Links.internetLog)576 try:577 internetLogField = FindByXpath("""//*[@id="content"]/div[3]/div/div[3]/div[2]/div/div/div[2]/form/textarea""")578 internetEditLogButton = FindByXpath("""//*[@id="content"]/div[3]/div/div[3]/div[2]/div/div/div[2]/form/input[2]""")579 except:580 if FindByXpath("/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div", shouldWait = True).text == "No logs":581 Print("Can't clear logs on " + ip)582 return583 Print("ERRORMAYBE InternetClearLog gets called again")584 InternetClearLog(ip, getIps, getBTCs)585 #Get log text586 rawLog = internetLogField.text587 logLines = rawLog.split("\n")588 #Clear the log589 internetLogField.clear()590 internetLogField.send_keys(signature)591 internetEditLogButton.click()592 #Wait the log to be cleared593 while WaitForLoad(Links.internetLog, errorPath = ErrorPath.internetLog) == False:594 if Error.processNotFound == errorText[1]:595 break596 if getBTCs:597 GetBTCFromLog(logLines)598 if getIps:599 GetIpsFromLog(logLines)600 Print("Log has been cleared on " + ip)601def Hack(ip = "1.2.3.4", clearLog = True, getSoftware = True, getIps = False, getBTCs = True):602 def WaitForLoadCalls(link):603 if WaitForLoad(link, errorPath=ErrorPath.login) == False:604 if Error.crackerNotGoodEnough == errorText[1]:605 Print("You're cracker isn't good enough to hack " + ip)606 return False607 elif Error.noCracker == errorText[1]:608 if cracker == "None":609 Print("No cracker set in settings.py")610 return False611 if Download(cracker):612 Install(cracker)613 else:614 return False615 return Hack(ip, clearLog, getSoftware, getIps, getBTCs)616 elif Error.login == errorText[1]:617 Print("Ip already in database")618 elif "Error!" == errorText[1]:619 Print("Retrying the hack")620 Hack(ip,clearLog,getSoftware,getIps,getBTCs)621 else:622 PrintLog("ERRORMAYBE Couldn't handle this error: " + errorText[1])623 WaitForLoad(link, errorPath=ErrorPath.login)624 #Hack host625 #Start by logging out if logged in to another IP626 browser.get(Links.internetLogout)627 #Then proceed to go to the ip requested628 browser.get(Links.internetWithIp + ip)629 #Enter the hacking GUI630 browser.get(Links.internetHack)631 #Start bruteforcing632 browser.get(Links.internetBruteforce)633 #Check if the ip still exists634 #This should return false if635 ipInputField = FindByXpath('/html/body/div[5]/div[3]/div/div[1]/div[1]/div/div[1]/form/div/input[1]',shouldWait = False)636 if ip != ipInputField.get_attribute('value'):637 return False638 if WaitForLoadCalls(Links.internetLogin) == False:639 return False640 loginButton = FindByXpath('//*[@id="loginform"]/div[3]/span[3]/input', shouldWait = True)641 sleep(1)642 loginButton.click()643 if WaitForLoadCalls(Links.internet) == False:644 return False645 Print("Hacked " + ip)646 if clearLog:647 InternetClearLog(ip, getIps, getBTCs)648 if getSoftware:649 GetInternetSoftware(ip)650 return True651def DDos(ip, times = 1, hack = True, clearLog = True, getSoftware = True):652 #Launch ddos attack against ip x times653 def TimerStart():654 #Start timer / reset the start time655 global firstTime656 firstTime = clock()657 def TimerStop():658 #Return time since TimerStart()659 return clock() - firstTime660 def NewEstimatedTime(input, times):661 #Generate an estimatedTime662 global estimatedTime663 estimatedTime -= (estimatedTime-input)/times664 #If function is supposed to hack then do so665 if hack:666 if Hack(ip, clearLog, getSoftware) == False:667 Print("Failed hacking " + ip + " during the start of a ddos")668 return False669 else:670 Print("Successfully hacked " + ip)671 #Prepare estimatedTime time672 sleep(2)673 global estimatedTime674 estimatedTime = 305675 #Start ddosing x times676 for i in range(times):677 TimerStart()678 Print("")679 estimatedTimeLeft = str(RoundTime(datetime.datetime.now().time(), round(estimatedTime * (times-i))))680 Print ("Starting ddos number " + str(i+1) + "/" + str(times) + " against " + ip)681 Print ("This ETA: " + str(round(estimatedTime)) + " seconds, Total ETA: " + estimatedTimeLeft + " seconds")682 browser.get(Links.ddos)683 sleep(1)684 ipField = FindByXpath("""//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[1]/div/div[3]/form/div[1]/div/input""", shouldWait = True)685 try:686 launchDDosButton = FindByXpath("""//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[1]/div/div[3]/form/div[2]/div/input""")687 except:688 Print ("To ddos you need to have a breaker")689 try:690 if breaker == "None":691 Print("No breaker set in settings.py")692 return False693 if not Download(breaker):694 return False695 browser.get(Links.ddos)696 sleep(1)697 ipField = FindByXpath("""//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[1]/div/div[3]/form/div[1]/div/input""")698 launchDDosButton = FindByXpath("""//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[1]/div/div[3]/form/div[2]/div/input""")699 except:700 PrintLog("ERRORMAYBE DDOS EXCEPT IS NEEDED, RETURNING FALSE")701 return False702 ipField.send_keys(ip)703 launchDDosButton.click()704 sleep(2)705 Print("DDOS launched")706 WaitForLoad(Links.software, errorPath = ErrorPath.ddos)707 Print(ip + " has been DDosed, it took " + str(round(TimerStop())) + " seconds")708 NewEstimatedTime(TimerStop(),i+1)709 sleep(3)710 Print("Done DDosing " + ip)711if __name__ == "__main__":...

Full Screen

Full Screen

oldMain.py

Source:oldMain.py Github

copy

Full Screen

1#Import libraries2from selenium import webdriver3from time import sleep, clock, gmtime, strftime4import datetime5import re6import os7#Setup global vars8global ips9ips = []10global btcAddr11btcAddr = []12global btcPass13btcPass = []14########15# To-Do:16# Make the worm not upload ddosvirus to infected machines17# Find BTC info (it kinda works :D )18# Add input for hackedIps in worm.py19# Cleanup ErrorCheck20########21#Import settings if it exists22try: import settings23except NameError: pass24#Set vars from settings25try: debug = settings.debug26except NameError: debug = False27try: signature = settings.signature28except NameError: signature = ""29try: password = settings.password30except NameError: password = ""31try: userName = settings.userName32except NameError: userName = ""33try: firefox = settings.firefox34except NameError: firefox = False35try: breaker = settings.breaker36except NameError: breaker = "None"37try: cracker = settings.cracker38except NameError: cracker = "None"39#Setup Error strings and paths40class Error:41 crackerNotGoodEnough = "Error! Access denied: your cracker is not good enough."42 noCracker = "Error! You do not have the needed software to perform this action."43 login = "Error! This IP is already on your hacked database."44 invalidIp = "Error! Invalid IP address."45 notHacked = "Error! This IP is not on your Hacked Database."46 notUploaded = "Error! You do not have enough disk space to download this software."47 processNotFound = "Error! Process not found."48 fileHidden = "Error! This software already exists on your root folder."49 filePath = "/html/body/div[5]/div[3]/div/div/div[1]/strong"50 ddosPath = "/html/body/div[5]/div[3]/div/div/div/div[2]/div/div[1]/div/div[2]"51 logPath = "/html/body/div[5]/div[3]/div/div[1]/strong"52 notUploadedPath = "/html/body/div[5]/div[3]/div/div[1]/div[2]/strong"53 loginPath = "/html/body/div[5]/div[3]/div/div[1]/div[2]/strong"54#Setup links to the website55class Links:56 log = 'https://legacy.hackerexperience.com/log'57 home = 'https://legacy.hackerexperience.com/index.php'58 ddos = 'https://legacy.hackerexperience.com/list?action=ddos'59 software = 'https://legacy.hackerexperience.com/software'60 internet = 'https://legacy.hackerexperience.com/internet'61 harddisk = 'https://legacy.hackerexperience.com/software?page=external'62 download = harddisk + "&action=download&id="63 install = software + '?action=install&id='64 internetWithIp = internet + '?ip='65 internetHack = internet + '?action=hack'66 internetBruteforce = internet + '?action=hack&method=bf'67 internetLogin = internet + '?action=login'68 internetLog = internet + '?view=logs'69 internetSoftware = internet + '?view=software'70 internetLogout = internet + '?view=logout'71 internetInstall = internet + '?view=software&cmd=install&id='72 internetUpload = internet + '?view=software&cmd=up&id='73 internetHide = internet + '?view=software&cmd=hide&id='74def Start():75 #Make a dir called logs if it doesn't exist76 if not os.path.exists("logs"):77 os.makedirs("logs")78 #Make log file79 global logName80 logName = "logs\\" + datetime.datetime.now().strftime('%Y-%m-%d_%H;%M.log')81 #Start browser82 global browser83 if firefox == True:84 browser = webdriver.Firefox()85 else:86 chromeOptions = webdriver.chrome.options.Options()87 chromeOptions.add_argument('log-level=3')88 browser = webdriver.Chrome(chrome_options=chromeOptions)89 browser.set_window_size(970, 1045)90 browser.set_window_position(0, 0)91 browser.get('http://legacy.hackerexperience.com/')92 #Insert credentials93 loginButton = FindByXpath("""/html/body/div[2]/div[2]/div/div/div/ul/li[1]/a""")94 userNameField = FindByXpath("""//*[@id="login-username"]""")95 userPasswordField = FindByXpath("""//*[@id="password"]""")96 loginButton.click()97 userNameField.send_keys(userName)98 userPasswordField.send_keys(password)99 #Wait for user to login100 WaitForLoad(Links.home, reload = False, errorCheckBool = False)101 Print ("Logged in")102 #Set the yourIP global var to your ip103 global yourIp104 yourIp = YourIp()105def FindByXpath(xpath,errorExpected = True):106 #Find element by xpath, if errorExpected = false wait then wait for the xpath to be there107 if errorExpected:108 return browser.find_element_by_xpath(xpath)109 else:110 while True:111 try:112 return browser.find_element_by_xpath(xpath)113 except:114 sleep(1)115def RemoveElement(element):116 browser.execute_script("""117 var element = arguments[0];118 element.parentNode.removeChild(element);119 """, element)120def PrintDebug(inputString):121 #Write to log and only print to terminal if script is in debug mode122 inputString = str(RoundTime(datetime.datetime.now().time())) + " " + str(inputString)123 if debug:124 print(inputString)125 file = open(logName,"a")126 file.write(str(inputString) + "\n")127 file.close128def Print(inputString):129 #Write to log and print to terminal130 inputString = str(RoundTime(datetime.datetime.now().time())) + " " + str(inputString)131 print(inputString)132 file = open(logName,"a")133 file.write(str(inputString) + "\n")134 file.close135def RoundTime(currentTime, secs = 0):136 #Roundtime to nearest second137 newTime = datetime.datetime(100, 1, 1, currentTime.hour, currentTime.minute, currentTime.second)138 returnTime = newTime + datetime.timedelta(seconds=secs)139 return returnTime.time()140def TimerStart():141 #Start timer / reset the start time142 global firstTime143 firstTime = clock()144def TimerStop():145 #Return time since TimerStart()146 return clock() - firstTime147def NewEstimatedTime(input, times):148 #Generate an estimatedTime149 global estimatedTime150 estimatedTime -= (estimatedTime-input)/times151def ClearLog():152 #Clears user log153 browser.get(Links.log)154 logField = browser.find_element_by_name('log')155 editLogButton = FindByXpath("""//*[@id="content"]/div[3]/div/div/div/div[2]/div[2]/form/input[2]""", errorExpected = False)156 logField.clear()157 editLogButton.click()158 #Wait for the operation to finish and load the log site again159 WaitForLoad(Links.log)160 PrintDebug ("Log has been cleared")161def InternetClearLog(ip = "", getIps = False, getBTCs = False):162 #Clear the log on the connected machine163 PrintDebug ("Clearing log on " + ip)164 browser.get(Links.internetLog)165 try:166 internetLogField = FindByXpath("""//*[@id="content"]/div[3]/div/div[3]/div[2]/div/div/div[2]/form/textarea""")167 internetEditLogButton = FindByXpath("""//*[@id="content"]/div[3]/div/div[3]/div[2]/div/div/div[2]/form/input[2]""")168 except:169 if FindByXpath("/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div", errorExpected = False).text == "No logs":170 PrintDebug("No logs to be cleared on " + ip)171 return172 InternetClearLog(ip, getIps, getBTCs)173 #Get log text174 rawLog = internetLogField.text175 logLines = rawLog.split("\n")176 #Get the BtcPass and BtcAddr177 global btcAddr178 global btcPass179 if getBTCs:180 tempBtcAddr = []181 tempBtcPass = []182 for logLine in logLines:183 try:184 tempBtcAddr.append(re.search("[a-zA-Z0-9]{34}", logLine).group())185 tempBtcPass.append(re.search("[a-zA-Z0-9]{64}", logLine).group())186 except:187 pass188 if len(tempBtcAddr) == len(tempBtcPass):189 for i in range(0,len(tempBtcAddr)):190 if tempBtcAddr[-1] not in btcAddr:191 btcAddr.append(tempBtcAddr.pop())192 btcPass.append(tempBtcPass.pop())193 #Get ips from the log194 if getIps:195 for logLine in logLines:196 global ips197 foundIpList = re.findall( r'[0-9]+(?:\.[0-9]+){3}', logLine)198 for foundIp in foundIpList:199 if foundIp in ips:200 continue201 elif foundIp == yourIp:202 continue203 else:204 ips.append(foundIp)205 #Clear the log206 internetLogField.clear()207 internetLogField.send_keys(signature)208 internetEditLogButton.click()209 #Wait the log to be cleared210 if WaitForLoad(Links.internetLog, errorPath = Error.logPath) == False:211 if Error.processNotFound == errorText[1]:212 return False213 PrintDebug ("Log has been cleared on " + ip)214def YourIp():215 #Get your ip216 yourIp = FindByXpath("""/html/body/div[5]/div[1]/div/div[1]/span""", errorExpected = False)217 yourIp = yourIp.text218 return yourIp219def Install(software):220 #Install software locally221 PrintDebug ("Installing " + software)222 GetYourSoftware()223 try:224 i = yourSoftwares.index(software)225 PrintDebug(software + " is not in your softwares")226 except:227 return False228 browser.get(Links.install + yourIds[i])229 WaitForLoad(Links.software)230 PrintDebug (software + " installed")231 return True232def Download(software):233 #Download files from harddisk234 PrintDebug ("Downloading " + software)235 GetYourHarddisk()236 try:237 i = harddiskSoftwares.index(software)238 except:239 PrintDebug(software + " is not in harddisk")240 return False241 browser.get(Links.download + harddiskIds[i])242 #WaitForLoad(Links.software)243 if WaitForLoad(Links.software, errorPath=Error.filePath) == False:244 if Error.fileHidden == errorText[1]:245 PrintDebug(software + " is already on machine")246 return False247 PrintDebug (software + " downloaded")248 return True249def InternetInstall(software,ip=""):250 #Install file on internet machine251 PrintDebug ("Installing " + software + " on " + ip)252 GetInternetSoftware(ip)253 try:254 i = softwares.index(software)255 except:256 return False257 browser.get(Links.internetInstall + ids[i])258 WaitForLoad([Links.internet, Links.internetSoftware])259 PrintDebug (software + " installed" + " on " + ip)260 InternetClearLog(ip)261 return True262def InternetHide(software, ip=""):263 #Hide file on internet machine264 PrintDebug ("Hiding " + software + " on " + ip)265 GetInternetSoftware(ip)266 try:267 i = softwares.index(software)268 except:269 return False270 browser.get(Links.internetHide + ids[i])271 WaitForLoad([Links.internet, Links.internetSoftware])272 PrintDebug (software + " hid" + " on " + ip)273 InternetClearLog(ip)274 return True275def InternetUpload(software, ip=""):276 #Upload file to internet machine277 PrintDebug ("Uploading " + software + " on " + ip)278 GetYourSoftware()279 try:280 i = yourSoftwares.index(software)281 if yourIds[i] == "None":282 0/0283 except:284 Download(software)285 InternetUpload(software, ip)286 browser.get(Links.internetUpload + yourIds[i])287 WaitForLoad([Links.internet, Links.internetSoftware], errorPath = Error.notUploadedPath)288 if errorText[1] == Error.notUploaded:289 PrintDebug (software + " could'nt be uploaded" + " on " + ip)290 return False291 PrintDebug (software + " uploaded" + " on " + ip)292 InternetClearLog(ip)293 return True294def WaitForLoad(link, reload = True, errorCheckBool=True, errorPath = "null"):295 #Wait for a website to load296 if WaitForLoadErrorCheck(errorCheckBool,errorPath):297 return False298 ErrorCheck(errorPath)299 PrintDebug ("Wait for " + str(link) + " has loaded")300 while browser.current_url not in link:301 if reload:302 browser.refresh()303 #RemoveElement(FindByXpath('//*[@id="he2"]'), False)304 #RemoveElement(FindByXpath('//*[@id="gritter-notice-wrapper"]'),False)305 sleep(1)306 if WaitForLoadErrorCheck(errorCheckBool,errorPath):307 return False308 return True309def WaitForLoadErrorCheck(errorCheckBool,errorPath):310 #Function used in WaitForLoad, check if an error is present311 if errorPath != "null":312 if errorCheckBool:313 return ErrorCheck(errorPath)314 else:315 ErrorCheck(errorPath)316def ErrorCheck(errorPath):317 #Get string from the errorPath318 global errorText319 try:320 error = FindByXpath(errorPath)321 except:322 errorText = ["","None"]323 return False324 else:325 error = FindByXpath(errorPath.replace("/strong", ""))326 errorText = error.text.split("\n")327 try:328 PrintDebug(errorText)329 errorText.append(errorText[-1])330 except:331 PrintDebug("Error Return False 2")332 errorText = ["","None"]333 return False334 return True335def GetHDD(MB = True):336 #Get HHD returns float or int337 browser.get(Links.internetSoftware)338 fullHDD = FindByXpath("""/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div[2]/div/div[2]/span/font[2]""", errorExpected = False).text339 usedHDD = FindByXpath("""/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div[2]/div/div[2]/span/font[1]""", errorExpected = False).text340 if "GB" in fullHDD:341 fullHDD = float(fullHDD.replace(" GB", ""))342 fullHDD *= 1000343 else:344 fullHDD = float(fullHDD.replace(" MB", ""))345 if "GB" in usedHDD:346 usedHDD = float(usedHDD.replace(" GB", ""))347 usedHDD *= 1000348 else:349 usedHDD = float(usedHDD.replace(" MB", ""))350 if MB:351 return int(fullHDD - usedHDD)352 else:353 return (fullHDD - usedHDD)/1000354def GetInternetSpeed(Mbit = True):355 #Get Internetspeed returns int or float356 browser.get(Links.internetSoftware)357 internetSpeed = FindByXpath("""/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div[2]/div/div[1]/span/strong""", errorExpected = False).text358 if "Gbit" in internetSpeed:359 internetSpeed = int(internetSpeed.replace(" Gbit", ""))360 internetSpeed *= 1000361 else:362 internetSpeed = int(internetSpeed.replace(" Mbit", ""))363 if Mbit:364 return internetSpeed365 else:366 return internetSpeed/1000367def GetYourHarddisk():368 #Get all important data from your harddisk369 browser.get(Links.harddisk)370 global harddiskIds371 global harddiskSoftwares372 global harddiskVersions373 global harddiskSizes374 harddiskIds = ["None"]375 harddiskSoftwares = ["None"]376 harddiskVersions = ["None"]377 harddiskSizes = ["None"]378 i = 0379 PrintDebug("Getting harddisk software")380 try:381 while True:382 i += 1383 baseXpath = "/html/body/div[5]/div[3]/div/div/div/div[2]/div[1]/table/tbody/"384 try:385 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[5]/a[1]")386 link = info.get_attribute('href')387 id = link.replace("https://legacy.hackerexperience.com/software?id=", "")388 except:389 id = "None"390 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[2]")391 software = info.text392 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[3]")393 version = info.text394 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[4]")395 size = info.text396 harddiskSizes.insert(i, size)397 harddiskVersions.insert(i, version)398 harddiskSoftwares.insert(i, software)399 harddiskIds.insert(i, id)400 except:401 pass402def GetYourSoftware():403 #Get all important data from your software404 browser.get(Links.software)405 global yourIds406 global yourSoftwares407 global yourVersions408 global yourSizes409 yourIds = ["None"]410 yourSoftwares = ["None"]411 yourVersions = ["None"]412 yourSizes = ["None"]413 i = 0414 PrintDebug("Getting your software")415 try:416 while True:417 i += 1418 baseXpath = "/html/body/div[5]/div[3]/div/div/div/div[2]/div/table/tbody/"419 try:420 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[5]/a[3]")421 link = info.get_attribute('href')422 id = link.replace("https://legacy.hackerexperience.com/software?action=install&id=", "")423 id = id.replace("https://legacy.hackerexperience.com/software?action=uninstall&id=", "")424 except:425 id = "None"426 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[2]")427 software = info.text428 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[3]")429 version = info.text430 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[4]")431 size = info.text432 yourSizes.insert(i, size)433 yourVersions.insert(i, version)434 yourSoftwares.insert(i, software)435 yourIds.insert(i, id)436 except:437 pass438def GetInternetSoftware(ip = "No ip was given"):439 #Get all important data from the connected machines software440 browser.get(Links.internetSoftware)441 global ids442 global softwares443 global versions444 global sizes445 ids = ["None"]446 softwares = ["None"]447 versions = ["None"]448 sizes = ["None"]449 i = 0450 PrintDebug("Getting software from " + ip)451 try:452 while True:453 i += 1454 baseXpath = "/html/body/div[5]/div[3]/div/div[3]/div[2]/div/div[1]/table/tbody/"455 try:456 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[5]/a[3]")457 link = info.get_attribute('href')458 id = link.replace("https://legacy.hackerexperience.com/internet?view=software&cmd=install&id=", "")459 id = id.replace("https://legacy.hackerexperience.com/internet?view=software&cmd=uninstall&id=", "")460 except:461 id = "None"462 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[2]")463 software = info.text464 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[3]")465 version = info.text466 info = FindByXpath(baseXpath + "tr[" + str(i) + "]/td[4]")467 size = info.text468 sizes.insert(i, size)469 versions.insert(i, version)470 softwares.insert(i, software)471 ids.insert(i, id)472 WriteToFiles(ip, 2, i)473 for j in range(1,10):474 WriteToFiles(ip, j*10, i)475 except:476 pass477def DDos(ip, times = 1, hack = True, clearLog = True, getSoftware = True):478 #Launch ddos attack against ip x times479 #If script is supposed to hack then do so480 if hack:481 if Hack(ip, clearLog, getSoftware) == False:482 return False483 #Prepare estimatedTime time484 sleep(2)485 global estimatedTime486 estimatedTime = 305487 #Start ddosing x times488 for i in range(0,times):489 TimerStart()490 Print("")491 estimatedTimeLeft = str(RoundTime(datetime.datetime.now().time(), round(estimatedTime * (times-i))))492 Print ("Starting ddos number " + str(i+1) + "/" + str(times) + " against " + ip)493 Print ("This ETA: " + str(round(estimatedTime)) + " seconds, Total ETA: " + estimatedTimeLeft + " seconds")494 browser.get(Links.ddos)495 sleep(1)496 ipField = FindByXpath("""//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[1]/div/div[3]/form/div[1]/div/input""", errorExpected = False)497 try:498 launchDDosButton = FindByXpath("""//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[1]/div/div[3]/form/div[2]/div/input""")499 except:500 Print ("To ddos you need to have a breaker")501 try:502 if breaker == "None":503 Print("BREAKER IF, RETURN")504 return False505 if not Download(breaker):506 return False507 browser.get(Links.ddos)508 sleep(1)509 ipField = FindByXpath("""//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[1]/div/div[3]/form/div[1]/div/input""")510 launchDDosButton = FindByXpath("""//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[1]/div/div[3]/form/div[2]/div/input""")511 except:512 Print("DDOS EXCEPT IS NEEDED, RETURN")513 return False514 ipField.send_keys(ip)515 launchDDosButton.click()516 sleep(2)517 WaitForLoad(Links.software, errorPath = Error.ddosPath)518 '''519 if WaitForLoad(Links.software, errorPath = Error.ddosPath) == False:520 if "Success! DDoS attack against " + ip + " launched." == errorText[1]:521 WaitForLoad(Links.software, errorPath= """//*[@id="content"]/div[3]/div/div/div/div[2]/div/div[1]/div/div[3]/form/div[1]/div/input""")522 else:523 return False524 '''525 Print(ip + " has been DDosed, it took " + str(round(TimerStop())) + " seconds")526 NewEstimatedTime(TimerStop(),i+1)527 sleep(3)528 Print("Done DDosing " + ip)529def Hack(ip = "1.2.3.4", clearLog = True, getSoftware = True, getIps = False, getBTCs = False):530 #Hack host531 browser.get(Links.internetLogout)532 browser.get(Links.internetWithIp + ip)533 browser.get(Links.internetHack)534 browser.get(Links.internetBruteforce)535 if ip != FindByXpath("""/html/body/div[5]/div[3]/div/div[1]/div[1]/div/div[1]/form/div/input[1]""", errorExpected = False).get_attribute('value'):536 return False537 if WaitForLoad(Links.internetLogin, errorPath=Error.loginPath) == False:538 if Error.crackerNotGoodEnough == errorText[1]:539 return False540 elif Error.noCracker == errorText[1]:541 if cracker == "None":542 Print("CRACKER IF, RETURN")543 return False544 if Download(cracker):545 Install(cracker)546 else:547 return False548 return Hack(ip, clearLog, getSoftware, getIps, getBTCs)549 else:550 WaitForLoad(Links.internetLogin, errorPath=Error.loginPath)551 loginButton = FindByXpath("""/html/body/div[5]/div[3]/div/div[1]/div[3]/div[3]/form/div[3]/span[3]/input""", errorExpected = False)552 loginButton.click()553 if WaitForLoad(Links.internet, errorPath=Error.loginPath) == False:554 if Error.crackerNotGoodEnough == errorText[1]:555 return False556 elif Error.noCracker == errorText[1]:557 if cracker == "None":558 Print("CRACKER IF, RETURN")559 return False560 if Download(cracker):561 Install(cracker)562 else:563 return False564 return Hack(ip, clearLog, getSoftware, getIps, getBTCs)565 else:566 WaitForLoad(Links.internet, errorPath=Error.loginPath)567 Print ("Hacked " + ip)568 if clearLog:569 InternetClearLog(ip, getIps, getBTCs)570 if getSoftware:571 Print ("Getting software information from " + ip)572 GetInternetSoftware(ip)573 return True574def WriteToFiles(ip, minSoftwareVersion, i):575 #WriteToFiles is used for logging576 if minSoftwareVersion <= float(versions[i]):577 with open("software" + str(minSoftwareVersion) + ".txt", "a") as myfile:578 myfile.write(ip + ": " + softwares[i] + " " + versions[i] + " " + sizes[i] + "\n")579if __name__ == "__main__":...

Full Screen

Full Screen

nztravel.py

Source:nztravel.py Github

copy

Full Screen

1#!/usr/bin/python32# -*- coding: utf-8 -*-3__author__ = ["Tuan Nguyen"]4__copyright__ = "Copyright 2018, Tuan Nguyen"5__credits__ = ["Tuan Nguyen"]6__license__ = "GPL"7__version__ = "1.0"8__status__ = "Production"9__author__ = "TuanNguyen"10__email__ = "etuannv@gmail.com"11__website__ = "https://etuannv.com"12# Start import other13from base import *14import shutil15import os16import sys17from urllib.parse import urljoin18from urllib.parse import quote_plus19from urllib.request import urlopen20import logging21import time22import requests23from time import sleep24import re25import csv26import json27import random28from datetime import datetime29from pytz import timezone30from datetime import timedelta31def checkContinue():32 result = False33 if os.path.exists(TempPath):34 #ask for continue35 os.system('clear')36 print ("============== ATTENTION !!! The previous session has not finished ==============")37 print("\n")38 is_continue = confirm(prompt='DO YOU WANT CONTINUE THE PREVIOUS SESSION?', resp=True)39 if not is_continue:40 logging.info("You choice start new session")41 print("\n")42 print("\n")43 try:44 # Delete all file in temp folder45 shutil.rmtree(TempPath)46 # Delete previous result47 # if ResultFileTempPath:48 # os.remove(ResultFileTempPath)49 except OSError:50 51 sys.exit("Error occur when delete temp folder")52 result = False53 else:54 logging.info("You choice continue previous session")55 print("\n")56 print("\n")57 result = True58 time.sleep(1)59 createFolderIfNotExists(TempPath)60 return result61def tryEnterEndDate(end_date_string):62 retry = 563 while retry > 0:64 retry -=165 tag = browser.findByXpath("//input[@id='ctl00_ContentPlaceHolder1_RadDatePicker2_dateInput']")66 tag.clear()67 tag.send_keys(end_date_string)68 time.sleep(.5)69 tag = browser.findByXpath("//input[@id='ctl00_ContentPlaceHolder1_RadDatePicker2_dateInput']")70 if tag:71 if end_date_string == tag.get_attribute('value'):72 return True73 return False74def enterSearchInfo(destination, start_date, end_date, age):75 start_date_string = '{}/{}'.format(start_date.day, start_date.strftime('%m/%Y'))76 end_date_string = '{}/{}'.format(end_date.day, end_date.strftime('%m/%Y'))77 while True:78 try:79 # Start enter value80 browser.selectDropdownByText("//select[@id='ContentPlaceHolder1_dpddestinat']", destination)81 tag = browser.findByXpath("//input[@id='ctl00_ContentPlaceHolder1_RadDatePicker1_dateInput']")82 tag.clear()83 tag.send_keys(start_date_string)84 time.sleep(3)85 tag = browser.findByXpath("//input[@id='ContentPlaceHolder1_txtAge1']")86 tag.clear()87 tag.send_keys(age)88 time.sleep(.3)89 90 # Enter end date91 res = tryEnterEndDate(end_date_string)92 if not res:93 chim_moi()94 continue 95 browser.sendKeys(Keys.TAB)96 time.sleep(.3)97 break98 except:99 chim_moi()100 time.sleep(3)101 pass102def getEssentials():103 value = ''104 note = ''105 # waiting for loading106 while browser.isExistByXPath("//div[@id='ContentPlaceHolder1_AjaxLoadingPanel1ContentPlaceHolder1_lblPremium_CS_D']//img", 0.1):107 time.sleep(0.1)108 time.sleep(1)109 tag = browser.findByXpath("//span[@id='ContentPlaceHolder1_lblPremium_CS_D']")110 if tag:111 value = tag.get_attribute('innerHTML')112 value = removeHtmlTag(value)113 value = getMoney(value)114 115 # get note116 tag = browser.findByXpath("//div[contains(@class,'essentials-color')]//p[@class='prod-info']/preceding-sibling::p[1]")117 if tag:118 temp = tag.get_attribute('innerHTML')119 if 'available to travellers up to 70 years old' in temp:120 note = 'Available up to age 70 only'121 return value, note122def getPremier():123 value = ''124 note = ''125 # waiting for loading126 while browser.isExistByXPath("//div[@id='ContentPlaceHolder1_AjaxLoadingPanel1ContentPlaceHolder1_lblPremium_TI_D']//img", 0.1):127 time.sleep(.1)128 time.sleep(1)129 tag = browser.findByXpath("//span[@id='ContentPlaceHolder1_lblPremium_TI_D']")130 if tag:131 value = tag.get_attribute('innerHTML')132 value = removeHtmlTag(value)133 value = getMoney(value)134 135 # Get note136 tag = browser.findByXpath("//div[contains(@class,'comprehensive-color')]//p[@class='prod-info']/preceding-sibling::p[1]")137 if tag:138 temp = tag.get_attribute('innerHTML')139 if 'available to travellers up to 70 years old' in temp:140 note = 'Available up to age 70 only'141 return value, note142def getFrequent():143 value = ''144 note = ''145 # waiting for loading146 while browser.isExistByXPath("//div[@id='ContentPlaceHolder1_AjaxLoadingPanel1ContentPlaceHolder1_lblPremium_TI_F']//img", 0.1):147 time.sleep(0.1)148 time.sleep(1)149 tag = browser.findByXpath("//span[@id='ContentPlaceHolder1_lblPremium_TI_F']")150 if tag:151 value = tag.get_attribute('innerHTML')152 value = removeHtmlTag(value)153 value = getMoney(value)154 155 # Get Note156 tag = browser.findByXpath("//div[contains(@class,'frequent-color')]//p[@class='prod-info']/preceding-sibling::p[1]")157 if tag:158 temp = tag.get_attribute('innerHTML')159 if 'available to travellers up to 70 years old' in temp:160 note = 'Available up to age 70 only'161 return value, note162def getDataFor(data):163 result = data.copy()164 run_date = datetime.now(timezone('Pacific/Auckland'))165 # Start = Run_Date + Departure166 # End = Start + Duration - 1167 departure = int(data['Departure'])168 # if departure > 364:169 # departure = 364170 start_date = run_date + timedelta(days=departure)171 end_date = start_date + timedelta(days=int(data['Duration']) - 1)172 result['Departure'] = departure173 result['Run_Date'] = run_date.strftime('%Y-%m-%d')174 result['Start'] = start_date.strftime('%Y-%m-%d')175 result['End'] = end_date.strftime('%Y-%m-%d')176 # Enter search info177 enterSearchInfo(data['Destination'], start_date, end_date, data['Age'])178 179 # waiting for loading180 181 while browser.isExistByXPath("//div[@id='ContentPlaceHolder1_AjaxLoadingPanel1ContentPlaceHolder1_lblPremium_CS_D']//img", 0.1):182 time.sleep(0.1)183 184 time.sleep(3)185 # Start to get data186 # import pdb; pdb.set_trace()187 # --- GET ESSENTIALS188 # click $250189 browser.tryClickByXpath("//input[@id='ContentPlaceHolder1_rdoExcessCS_D_0']", 5)190 result['Essentials250'], result['Essentials250_Note'] = getEssentials()191 # import pdb; pdb.set_trace()192 # click $100193 browser.tryClickByXpath("//input[@id='ContentPlaceHolder1_rdoExcessCS_D_1']", 5)194 result['Essentials100'], result['Essentials100_Note'] = getEssentials()195 196 # --- PREMIER197 # click $250198 browser.tryClickByXpath("//input[@id='ContentPlaceHolder1_rdoExcessTI_D_0']", 5)199 result['Premier250'], result['Premier250_Note'] = getPremier()200 201 # click $100202 browser.tryClickByXpath("//input[@id='ContentPlaceHolder1_rdoExcessTI_D_1']", 5)203 result['Premier100'], result['Premier100_Note'] = getPremier()204 # click $0205 browser.tryClickByXpath("//input[@id='ContentPlaceHolder1_rdoExcessTI_D_2']", 5)206 result['Premier0'], result['Premier0_Note'] = getPremier()207 # FREQUENT TRAVELLER208 # click $250209 browser.tryClickByXpath("//input[@id='ContentPlaceHolder1_rdoExcessTI_F_0']", 5)210 result['Frequent250'], result['Frequent250_Note'] = getFrequent()211 # click $100212 browser.tryClickByXpath("//input[@id='ContentPlaceHolder1_rdoExcessTI_F_1']", 5)213 result['Frequent100'], result['Frequent100_Note'] = getFrequent()214 # click $0215 browser.tryClickByXpath("//input[@id='ContentPlaceHolder1_rdoExcessTI_F_2']", 5)216 result['Frequent0'], result['Frequent0_Note'] = getFrequent()217 218 219 return result220def chim_moi():221 logging.info("Chim moi")222 while True:223 try:224 browser.getUrl('https://www.nz-travel-insurance.co.nz')225 time.sleep(5)226 browser.selectDropdownByText("//select[@id='ContentPlaceHolder1_Widget_dpddestinat']", 'United States')227 tag = browser.findByXpath("//input[@id='ContentPlaceHolder1_Widget_txtpeople']")228 tag.clear()229 tag.send_keys('1')230 tag = browser.findByXpath("//input[@id='ContentPlaceHolder1_Widget_txtAge1']")231 tag.clear()232 tag.send_keys('33')233 234 tag = browser.findByXpath("//input[@id='ctl00_ContentPlaceHolder1_Widget_RadDatePicker1_dateInput']")235 tag.clear()236 tag.send_keys('18/06/2019')237 time.sleep(3)238 239 # try to enter enddate240 retry = 5241 while retry > 0:242 retry -=1243 tag = browser.findByXpath("//input[@id='ctl00_ContentPlaceHolder1_Widget_RadDatePicker2_dateInput']")244 tag.clear()245 tag.send_keys('20/06/2019')246 tag = browser.findByXpath("//input[@id='ctl00_ContentPlaceHolder1_Widget_RadDatePicker2_dateInput']")247 if tag:248 if '20/06/2019' == tag.get_attribute('value'):249 break250 251 browser.findByXpath("//input[@id='ContentPlaceHolder1_Widget_btnQuote']").click()252 253 time.sleep(3)254 break 255 except:256 time.sleep(3)257 pass258 259def main(argv):260 global browser, CurrentPath, TempPath261 CurrentPath = os.path.dirname(os.path.realpath(sys.argv[0]))262 InputFilePath = os.path.join(CurrentPath, 'input.csv')263 TempPath = os.path.join(CurrentPath, 'temp_result')264 ResultTempFilePath = os.path.join(TempPath, "result.csv")265 DoneCheckFilePath = os.path.join(TempPath, "done_item.txt")266 # ======= CHECK IF WANT TO CONTINUE PREVIOUS SESSION ========267 checkContinue()268 # ======= READ PROXY IF ANY ========269 PROXY_LIST = [270 'us-il.proxymesh.com',271 'us.proxymesh.com',272 'us-dc.proxymesh.com',273 'us-ca.proxymesh.com',274 'us-wa.proxymesh.com',275 'open.proxymesh.com',276 ]277 proxyArgsList = []278 for proxy in PROXY_LIST:279 proxyArgsList.append({280 'proxy_host': '{}'.format(proxy),281 'proxy_port': 31280,282 'proxy_user': 'your user',283 'proxy_pass': 'your password',284 })285 286 287 # ======= READ PREVIOUS SESSION ========288 # Get done category url list289 done_list = readTextFileToList(DoneCheckFilePath)290 # ======= START MAIN PROGRAM ========291 # READ INPUT FILE292 input_data, header = readCsvToListDict(InputFilePath)293 294 if not len(input_data) > 0:295 logging.info('Input file path: {}'.format(InputFilePath))296 sys.exit("No input data")297 298 299 # changeProxyTotal =50 -- Change proxy each 50 requests 300 #browser = WebBrowser(timeout = 10, isDisableImage = True, isDisableJavascript = False, proxyArgsList=proxyArgsList, changeProxyTotal=50)301 browser = WebBrowser(timeout = 10, isDisableImage = False, isDisableJavascript = False)302 chim_moi()303 counter = 0304 total = len(input_data)305 # header.append('url')306 for data in input_data:307 counter +=1308 logging.info("Process {}/{}".format(counter, total))309 identify_data = '{}, {}, {}, {}'.format(data['Destination'], data['Age'], data['Departure'], data['Duration'])310 if identify_data in done_list:311 continue312 if 0 == counter%20:313 chim_moi()314 result = getDataFor(data)315 316 317 if result is not None:318 writeDictToCSV([result], ResultTempFilePath, 'a', header)319 320 # Write done file321 writeListToTextFile([identify_data], DoneCheckFilePath, 'a')322 323 browser.exitDriver() 324 # ========= POST DONE ===========325 # Move result file to project directory326 if os.path.exists(TempPath):327 final_result_path = os.path.join(CurrentPath, 'result_at_{}'.format(getCurrentDateString("%Y%m%d_%H%M%S")))328 shutil.move(TempPath, final_result_path)329 # Rename temp folder330 # if os.path.exists(TempPath):331 # temp_done = os.path.join(CurrentPath, "temp_at_" + getCurrentDateString("%Y%m%d_%H%M%S"))332 # shutil.move(TempPath, temp_done)333 #shutil.rmtree(TempPath)334 return True335if __name__ == "__main__":336 main(sys.argv)337 logging.info("DONE !!! etuannv@gmail.com ;)")...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run websmith automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful