Test archive data (unzip -t equivalent) - Python - python

I have a program written in python that uploads an archive (zip file) to a remote server. But before uploading it I need to test that it is not corrupted, so I want to execute something like an unzip -t and throw an error if it fails.
Is there something implemented in python that can do that (couldn't find anything on google), or is there a way to catch the error from my program if I execute the system call unzip -t?
Thanks

Zipfile.testzip is your friend.
Read all the files in the archive and check their CRC’s and file headers. Return the name of the first bad file, or else return None.

Use ZipFile.testzip:
import zipfile
def zip_isOk(fn):
with zipfile.ZipFile(fn, 'r') as zipf:
return zipf.testzip() is None

Related

b'Error could not find or load main class caused by java.lang.classnotfoundation error'

I am trying to read the executable jar file using python. That jar file doesn't have any java files. It contains only class and JSON files.
So what I tried is
from subprocess import Popen,PIPE
jar_location = C:\\users\app\\my_file.jar"
inputs = C:\\users\\app\my_input.json"
my_data = Popen(["java", "-cp",jar_location,"SOMECLASS.class",inputs])
stdout,stderr = my_data.communicate()
print(stdout,stderr)
What my expected output is, it reads the input(inputs) and passes it to the given class method(someclass.class) and it should return some response for me.
But the actual output I am getting is a Class file not found error.
The class file is inside the jar file only
I tried with Popen(["java",""-jar",jar_location,inputs]), I am getting no main manifest attribute found. I can see a manifest file with the basic version.
Can someone help me how to read these class files through python? I have to do the same thing for multiple class files which are inside the jar file
You should not specify a filename inside a JAR file, but a class name. Try with
my_data = Popen(["java", "-cp", jar_location, "SOMECLASS",inputs])
(omit the ".class" extension please)
You find the documentation of the java tool (that you use to execute your jar-file) as The java tool in the collection of the JDK Tool Specifications
The synopsis variant you are using is
java [options] mainclass [args ...], you gave the option for the classpath -cp <classpath> and you use the JAR-file as only element in the classpath.
Please note that if the JAR-file contains a MANIFEST.MF file, when you open it with a ZIP-tool, you should inspect that because it could contain a longer classpath that you might have to specify also on commandline, if you don't use the -jar parameter. A manifest doesn't always contain a main-class that is used for the execution via -jar, but still can contain other important parameters. And the values are always trimmed to a short line-length inside that file, don't get confused by that.

Successful unzip with wrong password

My specific question is around what exactly zipfile.ZipFile(myfile.zip).extractall(thepassword) actually does. I'm working through some pentest tutorials and have written the following snippet.
There are two files that the script acts upon. The first is a zip file that was created using zip -P very_long_random_string_password -r myfile.zip myfiles.txt. This is on Kali Linux from the CLI with Python3 (3.9). The second file is a list of common passwords from github ([passlist.txt][1]).
#Python3
from zipfile import ZipFile
with open('passlist.txt', 'r') as f:
for line in f:
password = line.strip('\n')
password = password.encode('utf-8')
try:
foundpass = ZipFile('myfile.zip').extractall(pwd=password)
if foundpass == None:
print("\nPassword: ", password.decode())
break
except RuntimeError:
pass
The expected result would be for the script to try every password in the passlist.txt and if the extractall method didn't throw a RuntimeError to print out the successful password. If the password is wrong, the program continues.
This in fact does work and I've tried multiple passwords that are caught as expected based on passwords in the passlist.txt. BUT... I wanted to have the script run unsuccessfully and got an unexpected result.
Using a -P pashdshGivgisudhfagn9879te6rtq6rr in the zip process, which doesn't exist in the passlist.txt resulted in successfully unlocking the zip file using the password rabbit11. As it turns out I can unzip the file with rabbit11 or pashdshGivgisudhfagn9879te6rtq6rr.
I've run this several times now with different very_long_random_string_passwords and been able to find corresponding simple_passwords that will unlock the zip file.
Why? I don't see any pattern to encoded text and this seems to be odd behavior.
Other examples (I actually haven't found one that doesn't work):
Complex: 444hdshGivgisudhfagn9879te6rtq6rr
Simple: rugby12
Complex: rszv8FoGGM6JRWGX
Simple: lickme

PYTHON AND BATCH SCRIPT: Run file if it exists and create if it doesn't

Full Disclaimer: I DO NOT KNOW PYTHON.
Hi Guys,
I have made an AutoHotKey Script for my volume keys. I would like to create a batch file which runs a python file (so if I change computers, I can easily create this scripts) which would do the following
Check if volume_keys.ahk exists in the D Drive
If it exists, run that;
If it doesn't exist, then create a file named volume_keys.ahk and add my script to it.
My script is:
^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down}
I know how to code the .bat file and just need help for the python point-of-view, but I request the community to check it:
#ECHO OFF
ECHO This script will run an AHK Script. If you want to stop this process from happening, then cross this window off.If you want to continye:
pause
cd d:
D:\run_volume_keys_ahk_script.py
I really appreciate any help by the community.
Thanks in advance
You can use the os library for this. Here's what the python program would look like.
import os
if os.path.isfile('D:\\volume_keys.ahk'): # check if it exists
os.system('D:\\volume_keys.ahk') # execute it
else:
with open('D:\\volume_keys.ahk', 'w') as f: # open it in w (write) mode
f.write('^!NumpadMult::Send {Volume_Mute} \
^!NumpadAdd::Send {Volume_Up} \
^!NumpadSub::Send {Volume_Down}') # Write to file
os.system('D:\\volume_keys.ahk') # execute
To activate the ahk script, you might want to use the subprocess module, of which I took the example from here
import subprocess
subprocess.call(["path/to/ahk.exe", "script.ahk"])
Note that you'll have to find the ahk executable on a computer before you can use the script, maybe you want to automatically check that too.
You can set the path you want to check for scripts in one string, and then add the filenames of your scripts as strings to a list. You can use listdir() from the os module to see any files and directories at a given path, then iterate over your scriptnames and check if it exists in that list of files. If it does, run it.
In this example I copy-pasted your script into a string as value for the key 'scriptname' in a dictionary, so that python can actually create the script file. This isn't really a neat way to do it though, you might want to have your scripts prepared in a directory next to your python script and copy them from there. See an example of how here
from os import listdir
from os.path import isfile, join
CHECK_PATH = "D:"
AHK_EXECUTABLE_PATH = "path/to/ahk.exe"
SCRIPTS_TO_CHECK = {'script1.ahk':"""^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down} """, 'script2.ahk':" some other script here"}
files_to_check = set(listdir(CHECK_PATH)) # using a set for fast lookup later
for scriptname, script in SCRIPTS_TO_CHECK.items():
if not scriptname in files_to_check:
print(f"script {scriptname} not found, creating it.")
with open(scriptname, 'w') as file:
file.write(script)
# else
subprocess.call(AHK_EXECUTABLE_PATH, scriptname)

How to get files written by the micro:bit to the PC?

I am new to BBC micro:bit, so I have the following Problem:
I want to read movements and write it to a file on the m:b and after all I want to download it from there to the pc to work on it.
I wrote the file like that:
from microbit import *
with open('FileName.txt', 'w') as my_file:
my_file.write('text to write down')
I couldn't see the file, when I used the m:b as USB- device.
But when I programmed the m:b to list all files it wrote short before the file was on it.
I know, m:b has no disk operating System, so I tried to pull it with python code, I started the following python code on a Windows pc:
(see: Docs to microfs)
import microfs
print microfs.ls()
But I got the error IOError: Could not find micro:bit.
The m:b is not found, I suppose.
What am I doing wrong? What else could I try?
Sometimes if the micro:bit cannot be found by scripts like uFlash or MicroFs it helps if you unplug the USB cable, wait a few seconds and plug it again (an additional note for Linux users, although I am aware that this is not the case for you, on Linux is also helpful to wait until the micro:bit drive has been mounted).
You are in the right track using MicroFs to access the MicroPython files, as they are in the microcontroller flash, and not accessible through the USB mass storage interface. Remember that writing a new program into the micro:bit does erase all of the flash contents, including any files your previous program might have created.
For easy of use I would recommend using the Mu editor (https://codewith.mu), as it offers you a GUI to move files in and out of the micro:bit. It's worth noting that Mu uses uFlash and MicroFs internally, so it will give you the same results as using those individual command line tools.
I, too, have spent several hours searching for the answer to getting microfs and mu to read a file from the microbit, after receiving the 'can't find it' message.
I have just found a solution: update the microbit firmware.
I have flashed an empty Python file from mu to the microbit and then used the command line ufs put <path to file>\main.py to copy over code that creates a text file and displays a heart on the microbit.
Now the Files option in mu correctly displays main.py and the created text file on my microbit.
I hope this helps.
As mentioned, you can use the command line ufs to put, get, list and delete files on the microbit.
pip install microfs --user
Then use ufs to list, delete, put and get files on to and off the microbit.
github site: https://github.com/ntoll/microfs.
The commands are:
ufs ls #list files on the card
ufs rm <filename> # remove a file
ufs put <filename> # write a file to the micro:bit
ufs get <filename> # get a file from the micro:bit
First of all put a blank .py file on to the micro:bit. In Linux you can create this using:
touch empty.py
Connect with microbit by double clicking on it using your file browser (e.g. Nautilus in Linux).
Use mu to flash empty.py onto the microbit.
Then write your Micropython code and call it main.py. Use ufs to write main.py to the micro:bit.
ufs main.py
This file will run at reset and restart. You can have your main.py file import and use other Micropython files on the micro:bit. Put these onto the micro:bit using ufs.
ufs <file to import to main.py>.py
e.g.
ufs put utilities.py
The files can be overwritten using ufs put.
You can't use ufs and a repl at the same time.
Now you are in a position to write and read a text file. Please find two example functions I have used for this.
def read_file(filename):
with open(filename, 'r') as my_file:
read_value = my_file.read()
return read_value
def write_file(filename, value):
with open(filename, 'w') as my_file:
my_file.write(str(value))
my_file.close()
The files are written to the microbit and the data remains intact after repowering the device. The data file can be seen using:
ufs ls
Then copied to your local machine using:
ufs get <filename>

Microsoft Ajax Minifier output path access error when called from Python

I'm calling Microsoft Ajax Minifier from Python like so:
minifyArguments = ["C:\Program Files (x86)\Microsoft\Microsoft Ajax Minifier\AjaxMin.exe"]
for f in filesToMinify:
minifyArguments.append(f)
minifyArguments.append("–out")
minifyArguments.append("C:\\Users\\XXX\\Desktop\\TestFolder") #minifyJSDestinationPath
minifyArguments.append("–clobber")
ajaxMinProcess = subprocess.Popen(minifyArguments, shell=False)
stdout, stderr = ajaxMinProcess.communicate()
This works fine, and I see that it's starting etc. but when it wants to write the output file it gives an error:
AjaxMinifier.exe: error AM-AUTH: Access to the path 'C:\Users\XXX\Desktop\TestFolder' is denied.
I have tried different folders, the issue is not exclusive to the one in the code. It can't write to any folder.
When I don't call it from Python but directly from the commandline it works without problems.
Why does this happen and how can I fix it?
Thanks.
I found the solution to my problem:
This line:
minifyArguments.append("C:\\Users\\XXX\\Desktop\\TestFolder")
Should include the filename, like this:
minifyArguments.append("C:\\Users\\XXX\\Desktop\\TestFolder\\script.min.js")

Categories