pdfdump in python not working using scapy - python

#!/bin/bash/python3
from scapy3k.all import *``
import subprocess
import os
def ifac111():
pkts = sniff(filter="tcp", iface="tun0", count=100)
inp = input('want to see a \'pdfdump?\' \n Y/N--> ')
fag = pkts.summary()
print('-' * 60)
what_df = pkts.show()
print("^^^ Here you got {} packets {}.".format("100", "scanned"))
print("The {} ones are {} and second ones are just {} command".format("first", "summary", "show" ))
print(inp)
if inp == 'Y':
pkts[0].pdfdump()
else:
print("got ya \f hex0")
while 1 > 0:
SSS = input('enter your command\'s here:-> \t ') #\t moves 4 spaces
if SSS == 'packets':
ifac111()
elif SSS == 'nworkscan':
os.system('sudo nmap localhost/24')
elif SSS == 'Virusscan':
os.system('sudo chkrootkit')
elif SSS == 'clear':
subprocess.call('clear')
when i run the pdfdump i get this error
Traceback (most recent call last):
File "scapy2.py", line 27, in <module>
ifac111()
File "scapy2.py", line 16, in ifac111
pkts[0].pdfdump()
File "/usr/local/lib/python3.6/dist-packages/scapy3k/packet.py", line 418, in pdfdump
canvas = self.canvas_dump(**kargs)
File "/usr/local/lib/python3.6/dist-packages/scapy3k/packet.py", line 428, in canvas_dump
canvas = pyx.canvas.canvas()
NameError: name 'pyx' is not defined
sorry if the question is stupid I'm new with coding and been trying to do some research with no result I used ICMP instead of TCP also before on my old os but its not working after changing to parrot os and when I run pdfdump I get that error above

This is a bug in scapy3k.packet indeed - it tries to import pyx and silently continue if there's any import error, which leads to your problem:
try:
import pyx
except ImportError:
pass
You should fill a bug report in the project's github - the package should properly declare it's dependencies on 3rd part packages so they get installed alongside, and it should definitly not silence the fact that a required import failed.
In the meantime you can try installing pyx yourself - it might just work, or it might break elsewhere depending on versions compat.

You should use scapy instead of scapy3k, it contains those fixes and a better interception of PyX
FTR:
scapy3k = fork based on scapy 2.2.0 which used to be the only one supporting python 3
scapy (from secdev) = the original one, up-to-date that also works with python 3 since scapy 2.4.0+

Hard to believe this issue is still around after 3yrs. This is to inform anyone else who lands here wanting to know how to fix this problem.
It is due to "Intended" lazy import placed on the installation as it would require GB/s of downloaded files to support the TeX backend. Thus, this is an intentional error by the scapy project itself.
You need to install MikTeX and LiveTex as it is not evident.
LiveTex can be downloaded from here

Related

How to program hotstrings in python like in autohotkey

I want to make hotstrings in python that converts one word when typed into another after some processing, since AHK is very limiting when it comes to determining which word to type. Right now, I am using a hotstring in ahk that runs code on the command line that runs a python script with the word that I typed as arguments. Then I use pyautogui to type the word. However, this is very slow and does not work when typing at speed. I'm looking for a way to do this all with python and without ahk, but I have not found a way to do hotstrings in python. For example, every time I type the word "test" it replaces it with "testing." Thanks for your help. I'm running the latest version of Python and Windows 10 if that is useful to anyone by the way.
(if you want to process it as each letter is typed(t,te,tes,test), you should edit your question)
I call my SymPy functions using ahk hotkeys. I register the python script as a COM server and load it using ahk.
I do not notice any latency.
you'll need pywin32, but don't download using pip install pywin32
download from https://github.com/mhammond/pywin32/releases
OR ELSE IT WON'T WORK for AutoHotkeyU64.exe, it will only work for AutoHotkeyU32.exe.
make sure to download amd64, (I downloaded pywin32-300.win-amd64-py3.8.exe)
here's why: how to register a 64bit python COM server
toUppercase COM server.py
class BasicServer:
# list of all method names exposed to COM
_public_methods_ = ["toUppercase"]
#staticmethod
def toUppercase(string):
return string.upper()
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Error: need to supply arg (""--register"" or ""--unregister"")")
sys.exit(1)
else:
import win32com.server.register
import win32com.server.exception
# this server's CLSID
# NEVER copy the following ID
# Use "print(pythoncom.CreateGuid())" to make a new one.
myClsid="{C70F3BF7-2947-4F87-B31E-9F5B8B13D24F}"
# this server's (user-friendly) program ID
myProgID="Python.stringUppercaser"
import ctypes
def make_sure_is_admin():
try:
if ctypes.windll.shell32.IsUserAnAdmin():
return
except:
pass
exit("YOU MUST RUN THIS AS ADMIN")
if sys.argv[1] == "--register":
make_sure_is_admin()
import pythoncom
import os.path
realPath = os.path.realpath(__file__)
dirName = os.path.dirname(realPath)
nameOfThisFile = os.path.basename(realPath)
nameNoExt = os.path.splitext(nameOfThisFile)[0]
# stuff will be written here
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\${myClsid}
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{C70F3BF7-2947-4F87-B31E-9F5B8B13D24F}
# and here
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\${myProgID}
# HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Python.stringUppercaser
win32com.server.register.RegisterServer(
clsid=myClsid,
# I guess this is {fileNameNoExt}.{className}
pythonInstString=nameNoExt + ".BasicServer", #toUppercase COM server.BasicServer
progID=myProgID,
# optional description
desc="return uppercased string",
#we only want the registry key LocalServer32
#we DO NOT WANT InProcServer32: pythoncom39.dll, NO NO NO
clsctx=pythoncom.CLSCTX_LOCAL_SERVER,
#this is needed if this file isn't in PYTHONPATH: it tells regedit which directory this file is located
#this will write HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{C70F3BF7-2947-4F87-B31E-9F5B8B13D24F}\PythonCOMPath : dirName
addnPath=dirName,
)
print("Registered COM server.")
# don't use UseCommandLine(), as it will write InProcServer32: pythoncom39.dll
# win32com.server.register.UseCommandLine(BasicServer)
elif sys.argv[1] == "--unregister":
make_sure_is_admin()
print("Starting to unregister...")
win32com.server.register.UnregisterServer(myClsid, myProgID)
print("Unregistered COM server.")
else:
print("Error: arg not recognized")
you first need to register the python COM server:
first, get your own CLSID: just use a python shell.
import pythoncom
print(pythoncom.CreateGuid())
then, set myClsid to that output
to register:
python "toUppercase COM server.py" --register
to unregister:
python "toUppercase COM server.py" --unregister
hotstring python toUppercase.ahk
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
#SingleInstance, force
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
SetBatchLines, -1
#KeyHistory 0
ListLines Off
#Persistent
#MaxThreadsPerHotkey 4
pythonComServer:=ComObjCreate("Python.stringUppercaser")
; OR
; pythonComServer:=ComObjCreate("{C70F3BF7-2947-4F87-B31E-9F5B8B13D24F}") ;use your own CLSID
; * do not wait for string to end
; C case sensitive
:*:hello world::
savedHotstring:=A_ThisHotkey
;theActualHotstring=savedHotstring[second colon:end of string]
theActualHotstring:=SubStr(savedHotstring, InStr(savedHotstring, ":",, 2) + 1)
send, % pythonComServer.toUppercase(theActualHotstring)
return
f3::Exitapp
you can test the speed of hotstring hello world, it's very fast for me.
Edit def toUppercase(string): to your liking

make a python program have my UID to modificate a file

So, in short, I created a script (named main.py) in which there was a moment where I wrote in a file. It worked well. However, the permissions on this file had to be rwxrwxrw- and hence anyone could modify the file on the server. That's not what I wanted. So I changed the permissions to rwxrwxr-- and then I changed the code of main.py :
#!/usr/bin/python
import subprocess
text = "I want this text to appear in my file"
command = subprocess.Popen(["python", "modificateFile.py", str('"')+text+str('"')], stderr=subprocess.PIPE, stdout=subprocess.PIPE) #I run another file that will do the task
for i in command.stderr:
print(i.decode("utf-8")) #check if there is any error
code of modificateFile.py
#!/usr/bin/python
import platform
import os
import sys
UID = 1080 #my UID.. I don't really know if it's the right way to program this
if __name__ == "__main__":
system = platform.system()
if system == "Linux": #ok it may be useless
os.setuid(UID) # /!\ I THINK THAT'S WHERE THE PROBLEM IS /!\
if len(sys.argv) > 1:
with open("file.txt", "w", encoding="utf-8") as f:
f.write(sys.argv[1])
else:
sys.stderr.write("not enough parameters to work") #didn't know which error I could raise..
#so as I already imported sys, I used this function
exit(-1)
else:
sys.stderr.write("wrong OS : program only work on linux")
exit(-1)
When I created this, I didn't know really what I was doing to be honest… I am learning programming.
Error message:
Traceback (most recent call last): File "modificateFile.py", line 11,
in os.setuid(UID) PermissionError: [Errno 1] Operation not permitted
I heard of SUID.. but I don't have root permissions.
Could someone explain what is wrong and what I could do ?
(if you need more elements, tell me it)
ok…. I thought SUID was only available for root programs… I had already tested it for this program but it didn't work. However, I learnt after that SUID is not available for programs with a shebang at the beginning… So, I created a code in C to do that.

Compile Python code with Openpyxl into executable using PyInstaller Error cannot import '__versions__' [duplicate]

My traceback from running pandas takes me to:
site-packages\pandas\io\excel.py line 58, in get_writer
AttributeError: 'module' object has no attribute '__version__'
I found this link to a git issue in the PyInstaller repo
https://github.com/pyinstaller/pyinstaller/issues/1890 and found my openpyxl version, manually added it into the get_writer method like so:
def get_writer(engine_name):
if engine_name == 'openpyxl':
try:
import openpyxl
#remove when conda update available
openpyxl.__version__ = '2.3.2'
# with version-less openpyxl engine
# make sure we make the intelligent choice for the user
if LooseVersion(openpyxl.__version__) < '2.0.0':
return _writers['openpyxl1']
elif LooseVersion(openpyxl.__version__) < '2.2.0':
return _writers['openpyxl20']
else:
return _writers['openpyxl22']
except ImportError:
# fall through to normal exception handling below
pass
try:
return _writers[engine_name]
except KeyError:
raise ValueError("No Excel writer '%s'" % engine_name)
Still no dice. The line number given in the error traceback doesn't even change. I then updated the openpyxl version to 2.3.5, still receiving the error. The openpyxl init file has a version variable in it:
try:
here = os.path.abspath(os.path.dirname(__file__))
src_file = os.path.join(here, ".constants.json")
with open(src_file) as src:
constants = json.load(src)
__author__ = constants['__author__']
__author_email__ = constants["__author_email__"]
__license__ = constants["__license__"]
__maintainer_email__ = constants["__maintainer_email__"]
__url__ = constants["__url__"]
__version__ = constants["__version__"]
except IOError:
# packaged
pass
Any known or potential fixes or workarounds?
Edits were not making an impact because the process was compiled into an exe that these modules were running through. Exported the sections I needed outside of my anaconda environment and now the process works without a hitch.
I will add my workaround to this discussion as I was having the same problem using openpyxl 2.4.0 and maybe a few others are stuck too.
I found that to create a .exe file you have to revert to an older version of openpyxl. To do so:
Open the command prompt and uninstall openpyxl with 'pip uninstall openpyxl'
Reinstall openpyxl using an older version 'pip install openpyxl==2.3.5'
Now you should be able to create your .exe file using py2exe, cx_freeze, etc.
This is my fix: go to your openpyxl site-package folder (for me it's: C:\Python27\Lib\site-packages\openpyxl). Copy all variables in your .constant.json file directly into the _ init _.py file, so it looks like:
import json
import os
__author__= "See AUTHORS"
__author_email__= "eric.gazoni#gmail.com"
__license__= "MIT/Expat",
__maintainer_email__= "openpyxl-users#googlegroups.com"
__url__= "http://openpyxl.readthedocs.org"
__version__= "2.4.0"
try:
here = os.path.abspath(os.path.dirname(__file__))

Volatility plugin to extract config file from memory : Crashes after yara compile function

I am trying to write a Volatility plugin to extract configuration file used by a malware from memory dump. However, when I run this plugin (without 'sudo') without root privileges the plugin crashes at the line yara.compile. If I run this plugin with 'sudo', code after yara.compile line is not getting executed. I am not sure why yara.compile is causing this problem. Could someone help me with this? Following is the code I have written:
import volatility.plugins.common as common
import volatility.utils as utils
import volatility.win32.tasks as tasks
import volatility.debug as debug
import volatility.plugins.malware.malfind as malfind
import volatility.conf as conf
import volatility.plugins.taskmods as taskmods
try:
import yara
HAS_YARA = True
except ImportError:
HAS_YARA = False
YARA_SIGS = {
'malware_conf' : 'rule malware_conf {strings: $a = /<settings/ condition: $a}'
}
class malwarescan(taskmods.PSList):
def get_vad_base(self, task, address):
for vad in task.VadRoot.traverse():
if address >= vad.Start and address < vad.End:
return vad.Start
return None
def calculate(self):
if not HAS_YARA:
debug.error('Yara must be installed for this plugin')
print "in calculate function"
kernel_space = utils.load_as(self._config)
print "before yara compile"
rules = yara.compile(sources=YARA_SIGS)
print "after yara compile"
for process in tasks.pslist(kernel_space):
if "IEXPLORE.EXE".lower() == process.ImageFileName.lower():
scanner = malfind.VadYaraScanner(task=process, rules=rules)
for hit, address in scanner.scan():
vad_base_addr = self.get_vad_base(process, address)
yield process, address
def render_text(self, outfd, data):
for process, address in data:
outfd.write("Process: {0}, Pid: {1}\n".format(process.ImageFileName, process.UniqueProcessId))
So when I run this plugin with root privilege, I dont see the line "print 'after yara compile'" gets executed. What could be the reason? Thank you.
I installed "yara" through "pip". If you install yara through pip, you actually get yara-ctypes (https://github.com/mjdorma/yara-ctypes) which is a bit different than yara-python. So I uninstalled yara-ctypes and installed yara-python. Then it worked.

Executable out of script containing serial_for_url

I have developed a python script for making a serial communication to a digital pump. I now need to make an executable out of it. However even though it works perfectly well when running it with python and py2exe does produce the .exe properly when I run the executable the following error occurs:
File: pump_model.pyc in line 96 in connect_new
File: serial\__init__.pyc in line 71 in serial_for_url
ValueError: invalid URL protocol 'loop' not known
The relevant piece of my code is the following:
# New serial connection
def connect_new(self, port_name):
"""Function for configuring a new serial connection."""
try:
self.ser = serial.Serial(port = port_name,\
baudrate = 9600,\
parity = 'N',\
stopbits = 1,\
bytesize = 8,\
timeout = self.timeout_time)
except serial.SerialException:
self.ser = serial.serial_for_url('loop://',\
timeout = self.timeout_time) # This line BLOWS!
except:
print sys.exc_info()[0]
finally:
self.initialize_pump()
I should note that the application was written in OSX and was tested on Windows with the Canopy Python Distribution.
I had the exact same problem with "socket://" rather than "loop://"
I wasn't able to get the accepted answer to work however the following seems to succeed:
1) Add an explicit import of the offending urlhandler.* module
import serial
# explicit import for py2exe - to fix "socket://" url issue
import serial.urlhandler.protocol_socket
# explicit import for py2exe - to fix "loop://" url issue (OP's particular prob)
import serial.urlhandler.protocol_loop
# use serial_for_url in normal manner
self._serial = serial.serial_for_url('socket://192.168.1.99:12000')
2) Generate a setup script for py2exe (see https://pypi.python.org/pypi/py2exe/) -- I've installed py2exe to a virtualenv:
path\to\env\Scripts\python.exe -m py2exe myscript.py -W mysetup.py
3) edit mysetup.py to include option
zipfile="library.zip" # default generated value is None
(see also http://www.py2exe.org/index.cgi/ListOfOptions)
3) build it:
path\to\env\Scripts\python.exe mysetup.py py2exe
4) run it
dist\myscript.exe
Found it!
It seems that for some reason the 'loop://' arguement can't be recognised after the .exe production.
I figured out by studying the pyserial/init.py script that when issuing the command serial.serial_for_url(‘loop://') you essentially call:
sys.modules['serial.urlhandler.protocol_loop’].Serial(“loop://“)
So you have to first import the serial.urlhandler.protocol_loop
and then issue that command in place of the one malfunctioning.
So you can now type:
__import__('serial.urlhandler.protocol_loop')
sys.modules[‘serial.urlhandler.protocol_loop’].Serial("loop://")
After this minor workaround it worked fine.

Categories