Write a file in Python 2.7 without getting blocked by Windows? - python

I'm writing a simple fuzzer for use on Windows applications based on the Charlie Miller code from the babysitting an army of monkeys talk. However I keep receiving the error
Traceback (most recent call last):
File "D:/Python27/fuzzer.py", line 29, in <module>
process=subprocess.Popen([app_choice,fuzz_output])
File "D:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "D:\Python27\lib\subprocess.py", line 896, in _execute_child
startupinfo)
WindowsError: [Error 5] Access is denied
Does anyone know how to bypass this? I'm really stumped because I'm not all too familiar with Windows 7 permissions or Python 2.7 to be honest. Full code below
#List of file names (all located in the python folder)
fuzz_files=[ "slides_algo-guiding.pdf", "slides_algo-intro-annotated- final.pdf","slides_algo-merge1.pdf"]
apps=["C:\Program Files (x86)\Adobe\Reader 9.0\Reader"
]
#Creates an output file in the Python folder
fuzz_output="fuzz.pdf"
FuzzFactor=50
num_tests=1000
import math
import string
import random
import subprocess
import time
for i in range(num_tests):
file_choice=random.choice(fuzz_files)
app_choice=random.choice(apps)
buf=bytearray(open(file_choice,'rb').read())
#Charlie Miller code
numwrites=random.randrange(math.ceil((float(len(buf))/FuzzFactor)))+1
for j in range(numwrites):
rbyte=random.randrange(256)
rn=random.randrange(len(buf))
buf[rn]="%c"%(rbyte)
#End Charlie miller code
#Write code
open(fuzz_output,'wb').write(buf)
process=subprocess.Popen([app_choice,fuzz_output])
time.sleep(1)
crashed=process.poll()
if not crashed:
process.terminate()

I believe that C:\Program Files (x86)\Adobe\Reader 9.0\Reader is the path of a folder, not an executable. Therefore trying to run it with Popen makes no sense.
Also, you should be using raw strings when writing Windows paths r"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe" or using slashes instead "C:/Program Files (x86)/Adobe/Reader 9.0/Reader/AcroRd32.exe". You were just lucky that there weren't any valid escape sequences in the paths.

Related

How to make a Python script "tab-complete" directories in terminal?

I have a Shell Script, let's say run.sh, which reads a user input from keyboard and then does some specific tasks. For some technical reasons I'm migrating this script to Python, e.g run.py, in order to achieve the exact same goal.
In the run.sh file I ask the user a input, which is typically a file in the file system, so I gave the option of "tab-completing" it and I achieved it simply through the line:
read -e -p "Choose a file: " file
The -e flag does the job of tab-completing users input. For example, if user's current directory is project, which follows the structure:
project
-- src
-- shared
-- lib
-- imgs
-- image.png
-- include
-- README.txt
and the input file is image.png they could proceed as follow:
sh<tab>i<tab><tab>
the result would be shared/imgs/image.png.
Now how do I achieve it inside a Python script? You may believe there are tons of related questions but I haven't been able to reproduce this exact same result in run.py.
What I have tried so far:
1. Python's os module:
import os
os.system("read -e -p 'Choose a file:'")
Output: sh: 1: read: Illegal option -e
2. Python's subprocess module
import subprocess
subprocess.run(['read', '-e', '-p', 'Choose a file'])
Output:
Traceback (most recent call last):
File "run.py", line 26, in <module>
subprocess.run(['read', '-e', '-p', 'Choose a file'])
File "/usr/lib/python3.7/subprocess.py", line 453, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib/python3.7/subprocess.py", line 756, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.7/subprocess.py", line 1499, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'read': 'read'
3. Python's readline module
import readline
readline.parse_and_bind("tab:complete")
file = input("Choose a file: ")
This one almost seems to work, but there is one big issue: it completes only the files in user's current directory. If user hit s<tab> then src and shared show up, but if they hit sh<tab> the liband imgs directory do not show up.
I'd like some elegant and simple way to achieve this, but I am convinced this might be a little more difficult than expected. Are there any other approaches that can solve this problem?
Set sensible completion delimiters:
import readline
readline.set_completer_delims(' \t\n=')
readline.parse_and_bind("tab: complete")
option = input("Tab complete a file: ")
By default, readline will delimit based on any of the following:
>>> import readline
>>> readline.get_completer_delims()
' \t\n`~!##$%^&*()-=+[{]}\\|;:\'",<>/?'
Since / is part of this set, anything after a / will be completed independently of anything before it. This obviously makes no sense when you're trying to complete a file path.

Python script to check dir not working

I am stuck with my script at a point. The script is this
import subprocess
import os
def Windows():
SW_MINIMIZE = 6
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = SW_MINIMIZE
print(os.path.isdir("C:\Program Files (x86)"))
while True:
try:
subprocess.Popen(r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe', startupinfo=info)
except WindowsError:
subprocess.Popen(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
else:
try:
subprocess.Popen(r'C:\Program Files\Mozilla Firefox\firefox.exe', startupinfo=info)
except WindowsError:
subprocess.Popen(r'C:\Program Files\Google\Chrome\Application\chrome.exe', startupinfo=info)
What I want to do is check if the computer is 64 bit or 32 bit (as I want to open the browser without a window using subprocess.) to locate the browsers chrome or firefox, depending on which one the user has ( I am assuming that they have either one of them). Since the path for chrome and firefox varies in 64 vs 32 bit computers (Program Files and Program Files (x84)), I came up with this script which detects if x86 folder exists or not. If it does, it continues on the folder for searching for the browsers. However, if it doesn't, it assumes it is 32-bit and searches for Program Files folder and in that folder it searches for the browsers.
However, when I run the script I get this error
Traceback (most recent call last):
File "C:\Users\Charchit\Desktop\via.py", line 29, in <module>
Windows()
File "C:\Users\Charchit\Desktop\via.py", line 13, in Windows
subprocess.Popen(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
File "C:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
However, in my script it should not even go to while True Section because I have a 32 bit system and x86 folder doesn't exist!
You're not actually checking if os.path.isdir("C:\Program Files (x86)"). You're just printing it.
Instead of
print(os.path.isdir("C:\Program Files (x86)"))
while True:
You need to do
if os.path.isdir(r"C:\Program Files (x86)"):
Side note:
Both chrome and firefox traditionally place themselves on the path, so there's a good chance you can just do subprocess.Popen('firefox.exe') / subprocess.Popen('chrome.exe').
for creating the path use the built-ins python functions that won't mess up the path
if os.path.exists(os.path.join('C:', os.path.sep(), 'Program Files')):
# do your stuff

rar file module not working in python 2.7

i have a code like this
import rarfile
pwd = None
rar = rarfile.RarFile(source_filename)
rar.extractall(dest_dir,None,pwd) # error from here
this code in working in ubuntu.
when i run this on windows i get error like this
Traceback (most recent call last):
File "1_bete_rar.pyw", line 132, in extract
File "1_bete_rar.pyw", line 176, in unrar_file
File "rarfile.pyc", line 586, in extractall
File "rarfile.pyc", line 1112, in _extract
File "rarfile.pyc", line 1704, in custom_popen
File "subprocess.pyc", line 711, in __init__
File "subprocess.pyc", line 948, in _execute_child
WindowsError: [Error 2] The system cannot find the file specified
what is the problem with my code? how can i extract rar file with python in windows?
As the rarfile FAQ states (and as is made evident by traces of subprocess in the stack trace),
[rarfile] depends on unrar command-line utility to do the actual decompression.
Note that by default it expect it to be in PATH. If unrar launching fails, you need to fix this.
So get UnRAR from http://www.rarlab.com/rar_add.htm and put it somewhere in your PATH (such as the directory you're running your script from).
Looks like source_filename isn't pointing to a valid RAR file, do this little check before, just to be sure:
import os.path
os.path.isfile(source_filename) # what's the value returned?
If the file exists, then check if the path is in the correct format. For example, this won't work:
source_filename = 'c:\documents\file.rar'
Try this instead:
source_filename = 'c:\\documents\\file.rar'
Or even better, use raw strings:
source_filename = r'c:\documents\file.rar'
One common problem using python with Windows is that the path separator is \, but this is a special character that needs to be escaped in Python. If you print the source_filename you should be able to see if this is set correctly.
e.g.
source_filename = 'c:\users\prosserc\documents\myfile.txt'
will not work correctly. Here are a couple of alternatives:
Use a raw string:
source_filename = r'c:\users\prosserc\documents\myfile.txt'
or use os.path.join to join to an eviornment variable such as user_profile
source_filename = os.path.join(os.getenv('userprofile'), 'documents', 'myfile.txt')

cp: cannot stat ... No such file or directory

In a python script, I issue the command:
def copy_file(csv_file): #csv_file = "wpa-01.csv"
subprocess.call(["cp",csv_file,"tempfile.csv"])
I get the error:
cp: cannot stat 'wpa-01.csv' : No such file or directory
-tempfile.csv is a valid file, it is open
-I have tried adding quotes around wpa-01.csv, ie
subprocess.call(["cp","\"wpa-01.csv\"","tempfile.csv"])
-I have tried adding escape character in front of the '-'
-I have tried including the directory in front og the file name
-I am using gedit on a local Linux machine (so its not a dos2unix kind of solution), but the script is being ran on a remote Raspberry Pi
in every case I get the same error. I am at a loss for solutions. any suggestions?
***Here is the problem: "wpa-01.csv" is a 'live'/'dynamic' file. There is an active process that is updating that file in real time. I think that the file will have to be 'dead'/'static' in order to issue cp command? This is not ideal for my purposes. Is there a way to work around this like changing the mod or something? If not I suppose I can try to find an alternative solution.
print "wpa-01.csv" in os.listdir(".") #make sure file really does exist
subprocess.call(["cp","\"wpa-01.csv\"","tempfile.csv"],shell=True)
My guess is you need to set shell=True so that it uses your path to find cp executes in your shell ... if you don't use shell=True it wont use your path ...
Unfortunately all it is is a guess ...
Anyway, here is some supporting evidence:
>>> subprocess.call("copy tmp5.py tmp55.py")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\subprocess.py", line 470, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python26\lib\subprocess.py", line 623, in __init__
errread, errwrite)
File "C:\Python26\lib\subprocess.py", line 833, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>> subprocess.call("copy tmp5.py tmp55.py",shell=True)
1 file(s) copied.
0

Biopython error - The system cannot find the file specified

I have encountered an error which I am not able to resolve.
I am trying to perform the easiest set of commands that will perform a tBLASTn algorithm,
looking for a sequence (sequence specified as a "pytanie.fasta" file) in a database (also specified as file -> cucumber.fasta). The result will be saved in the "wynik.txt" file.
The code looks as following:
from Bio.Blast. Applications import NcbitblastnCommandline
database = r"\Biopython\cucumber.fasta"
qr = r"\Biopython\pytanie.fasta"
output = r"\Biopython\wynik.txt"
e = raw_input("Enter e-value: ")
tblastn_cline = NcbitblastnCommandline(cmd='blastn', db=database, query=qr, out=output, evalue=e, outfmt=7)
print tblastn_cline
stdout, stderr = tblastn_cline()
And the error I get:
File "C:\Users\IBM_ADMIN\Desktop\PYTHON\Workspace\Biopython\blast.py", line 20, in <module>
stdout, stderr = tblastn_cline()
File "C:\Python27\lib\site-packages\Bio\Application\__init__.py", line 435, in __call__
shell=(sys.platform!="win32"))
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 893, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
I am using:
Eclipse SDK Version: 3.7.1
Python version 2.7
OS: 64 bit Windows 7
I have tried this also on 32-bit Windows XP and it produces the same error.
Biopython package should work fine since it went through the tests suggested by biopython website. I have also tried other formats of the path where the files are located, but it did not work. My friend uses the same code on Ubuntu and it works fine.
Does anybody know how to fix this error?
What are the paths of the files?
The path r"\Biopython\cucumber.fasta", for example, is an absolute path on the current drive (because it starts with a backslash and no drive letter), which I think in your case is r"C:\Biopython\cucumber.fasta". Is that correct?

Categories