I have a simple CLI based program that I would like to add a GUI to. Optimally I would like to retain the ability to have this script run via the CLI as well. If this can be done, what is the best way to approach this? Disclaimer: I am relatively new to Tkinter!
from argparse import ArgumentParser
from ipaddress import IPv4Network
def Main():
""" Main Program """
parser = ArgumentParser(
description='Provided a list of IP addresses, format and output the correct fortigate commands to create them')
parser.add_argument('VDOM', help='Specify a VDOM', type=str)
parser.add_argument(
'File', help='Specify a file. Each entry should be on its own line, and have no extra characters', typ=str)
args = parser.parse_args()
with open(args.File, 'r') as input_file:
array = input_file.read().splitlines()
with open(args.vdom + '.txt', 'w') as output_file:
output_file.write("config vdom\n")
output_file.write("edit %s\n" % str(args.vdom))
output_file.write("config firewall address\n\n")
for i in range(0, len(array)):
try:
ip_addr = IPv4Network(array[i])
generateip(ip_addr, output_file)
except ValueError:
url = array[i]
generateurl(url, output_file)
def generateip(ip_addr, output_file):
"""
Generate a single IP address object.
ip_addr -- IP address network object
output_file -- an output text file
"""
output_file.write("edit \"%s\"\n" % str(ip_addr.with_prefixlen))
output_file.write("set color 1\n")
output_file.write("set subnet %s %s\n" %
(str(ip_addr.network_address), str(ip_addr.netmask)))
output_file.write("next\n\n")
def generateurl(url, output_file):
"""
Generate a single URL address object.
url -- A valid URL string
output_file -- an output text file
"""
output_file.write("edit %s\n" % url)
output_file.write("set color 1\n")
output_file.write("set type fqdn\n")
output_file.write("set fqdn %s\n" % url)
output_file.write("next\n\n")
if __name__ == '__main__':
Main()
Check out https://github.com/chriskiehl/Gooey . This will automatically convert your ArgParser arguments to a GUI. The GUI will be dependent on the code, so the root of your program still depends on the CLI.
Related
I am going to analyze the wireshark pcap file for the ARP packet. Perform a byte-level programming to read each byte and convert it to the ARP header element --- the sender MAC address, target MAC address, protocol type, etc.
Here is my code.
import argparse
import os
import sys
from scapy.all import *
def process_pcap(file_name):
print('Opening {}...'.format(file_name))
dstmac = []
srcmac = []
scapy_cap = rdpcap(file_name)
for pack in scapy_cap:
//if pack.type ==2054 then get ARP info
//????
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='PCAP reader')
parser.add_argument('--pcap', metavar='<pcap file name>',
help='pcap file to parse', required=True)
args = parser.parse_args()
file_name = args.pcap
if not os.path.isfile(file_name):
print('"{}" does not exist'.format(file_name), file=sys.stderr)
sys.exit(-1)
process_pcap(file_name)
sys.exit(0)
white_check_mark
eyes
raised_hands
I get only pack, but I don't know the way how to treat pack and get desired result.
pack is:
b'P\x9aL1\xb3\xfd\x08\x96\xad\xe8\x84]\x08\x00E\x00\x00m\x04\xe4#\x00u\x06*\xd8\r3\xb0\xbf\n\n\r\xd3\r=\xc1a\x9d\xa2\x1d=\xb5\xe4\xef6P\x18\xf7\xa2\xd1\xd6\x00\x00\x17\x03\x03\x00#\x00\x00\x00\x00\x00\x00\x03\x97\xc4\xee\x14[\x89\xd6 \xc7\xe6\xde\x8f\xe0\x13\xbc\x86\xffm"\xf6\x02q\x7f\xa1\xea\xdcu?\xa9\xaf\x01\x85\x02M\xc3\x14mX\x08\xf9\x99\x99\xc8A$\x0e\x93,\x90\xb9\x89[\x8f\x0b<W\xa3'
I've been written a .zip brute-forcer but I believe its continuing/trying to still find the password even though its found (The passwords are stored in a .txt which is called by Program.py -z zipname.zip -f filename.txt
I am unsure on how to stop the program once the password is found and halt the pool. Mainly because I am using multiprocessing.Pool. My code is as follows:
import argparse
import multiprocessing
import zipfile
parser = argparse.ArgumentParser(description="Unzips a password protected .zip", usage="Program.py -z zip.zip -f file.txt")
# Creates -z arg
parser.add_argument("-z", "--zip", metavar="", required=True, help="Location and the name of the .zip file.")
# Creates -f arg
parser.add_argument("-f", "--file", metavar="", required=True, help="Location and the name of the file.txt.")
args = parser.parse_args()
def extract_zip(zip_filename, password):
try:
with zipfile.ZipFile(zip_filename, 'r') as zip_file:
zip_file.extractall('Extracted', pwd=password)
print(f"[+] Password for the .zip: {password.decode('utf-8')} \n")
except:
# If a password fails, it moves to the next password without notifying the user. If all passwords fail, it will print nothing in the command prompt.
pass
def main(zip, file):
if (zip == None) | (file == None):
# If the args are not used, it displays how to use them to the user.
print(parser.usage)
exit(0)
# Opens the word list/password list/dictionary in "read binary" mode.
txt_file = open(file, "rb")
# Allows 8 instances of Python to be ran simultaneously.
with multiprocessing.Pool(8) as pool:
# "starmap" expands the tuples as 2 separate arguments to fit "extract_zip"
pool.starmap(extract_zip, [(zip, line.strip()) for line in txt_file])
if __name__ == '__main__':
main(args.zip, args.file)
Now usually file.txt has anywhere from hundreds of lines to thousands of lines (By thousands I really mean thousands; like 300k or 1500k). The password anywhere; from the first to the last line. I am unsure how to implement/place this 'handbreak' for once the password is found. I thought of using a break but that seemed incorrect as I was working with multiprocessing.Pool and also if I placed it after print() in try/except it would give outside loop error.
I did see this thread but wasn't sure if this would work for my instance; as I wasn't sure how could I express "password was found" and pass event/Event to def extract_zip(zip_filename, password)
Any help or guidance would be appreciated!
One way to do this is to use a Queue (or some other way to signal between processes).
To us a Queue, add lines in your main to create a Queue before creating the Pool:
m = multiprocessing.Manager()
q = m.Queue()
This gives you a shareable Queue which can be passed to the pool processes. Add the q to the arguments passed to your extract_zip() method. Then modify your extract_zip() method to use the q:
def extract_zip(zip_filename, password, que):
try:
with zipfile.ZipFile(zip_filename, 'r') as zip_file:
zip_file.extractall('Extracted', pwd=password)
print(f"[+] Password for the .zip: {password.decode('utf-8')} \n")
que.put('Done') # signal success
except:
# If a password fails, it moves to the next password without notifying the user. If all passwords fail, it will print nothing in the command prompt.
pass
You will need to use the async variety of StarMap. So your main method looks like:
def main(zip, file):
if (zip == None) | (file == None):
# If the args are not used, it displays how to use them to the user.
print(parser.usage)
exit(0)
# Opens the word list/password list/dictionary in "read binary" mode.
txt_file = open(file, "rb")
# create a Queue
m = multiprocessing.Manager()
q = m.Queue()
# Allows 8 instances of Python to be ran simultaneously.
with multiprocessing.Pool(8) as pool:
# "starmap" expands the tuples as 2 separate arguments to fit "extract_zip"
pool.starmap_async(extract_zip, [(zip, line.strip(), q) for line in txt_file])
pool.close()
q.get(True) # wait for a process to signal success
pool.terminate() # terminate the pool
pool.join()
You can add a timeout to the q.get() to handle cases where no password is found.
This is a simple code, its function is extracting the metadata of certain images. However, it would work on any linux machine via the terminal fine as expected, whether printing the metadata into the terminal or saving the result into a text file.
When it comes to CMD on windows which is the primary OS for my PC wouldn't work, even the shell IDLE for Python it doesn't create the file or even print out the metadata.
codes explanation, takes two parameters, name of image, and out << means whether it's supposed to output the data into the terminal or into a specified text file.
I can't actually spot where the problem is!!
Please help me to identify the issue !! Thanks
Here's the code:
from time import sleep
import argparse
from PIL import Image
from PIL.ExifTags import TAGS
def getMetaData(imgname, out):
"""supported format of images are: .JPG, .TIF & .WAV"""
try:
metaData = {} # dictionary to hold the tags
imgFile = Image.open(imgname)
print "Getting meta data..."
info = imgFile._getexif()
if info:
print "Found Meta Data! "
for (tag, value) in info.items():
tagname = TAGS.get(tag, tag) # to human readable format
metaData[tagname] = value
if not out:
print tagname, value
if out:
print "outputting to file ..."
with open(out, "w") as f:
for (tagname, value) in metaData.items():
f.write(str(tagname)+'\t'+str(value)+"\n")
except:
print "Failed!!"
def Main():
print "Coded By: GentleMan"
print "Created 2/24/2017"
print "Use it carefully baby"
print "Special for x6x.net"
sleep(3)
parser = argparse.ArgumentParser()
parser.add_argument("img", help="Name of an image File")
parser.add_argument("--output","-o", help="dump data out to File.")
args = parser.parse_args()
if args.img:
print getMetaData(args.img, args.output)
else:
print parser.usage
if __name__ == '__main__':
Main()
How can I select tray when I send a file to the printer with python-cups?
I have a very simple testprogram that looks like this:
#!/usr/bin/env python
import cups
import sys
if __name__ == '__main__':
filename = sys.argv[1]
conn = cups.Connection()
printers = conn.getPrinters()
printer_name = printers.keys()[0]
conn.printFile(printer_name, filename, "TestDoc", {})
print 'File "%s" sent to printer "%s"' % (filename, printer_name)
It sends the given file to the default printer with the default paper (tray=1). But I want the doc to be printed on paper from another tray (tray=5). How to I do that?
OR: Am I doing it the wrong way? Should I go about it some other way to get my doc to the printer? In my final app the doc exist only in memory and not on disk, the only reason for me to write it to disk would be if it was needed by the printing. Note that I would need to switch between trays for the docs I print.
I've been working on a Python problem for sometime now. I'm trying to use the Echoprint API to sort my music out. So i'm writing some code that does that for me.
This is how the API works :
Takes in a song name as a command line arg.
Gives the appropriate result.
But i'm writing a script that has to perform this "internally". As in, the script should take the files and perform the lookup and output the results to the terminal. (basically - NO COMMAND LINE ARGUMENTS SUPPLIED )
So is there anyway as to pass files into a function ?
I know this sounds silly but it's a problem i'm not able to solve.
If i use os.walk(), etc it returns a str object to my lookup function as a parameter. I want the audio file to be passed as a parameter.
Here's the code which takes in the song as a command line arg :
import sys
import os
import pyechonest.config as config
import pyechonest.song as song
config.CODEGEN_BINARY_OVERRIDE = os.path.abspath("/Users/******/python/minger/echoprint-codegen-master/echoprint-codegen")
config.ECHO_NEST_API_KEY='*****'
def lookup(file):
# Note that song.identify reads just the first 30 seconds of the file
fp = song.util.codegen(file)
if len(fp) and "code" in fp[0]:
# The version parameter to song/identify indicates the use of echoprint
result = song.identify(query_obj=fp, version="4.11")
print "Got result:", result
print result[0]
if len(result):
print "Artist: %s (%s)" % (result[0].artist_name, result[0].artist_id)
print "Song: %s (%s)" % (result[0].title, result[0].id)
else:
print "No match. This track may not be in the database yet."
else:
print "Couldn't decode", file
if __name__ == "__main__":
if len(sys.argv) < 2:
print >>sys.stderr, "Usage: %s <audio file>" % sys.argv[0]
sys.exit(1)
lookup(sys.argv[1])
From there, http://echonest.github.io/remix/apidocs/pyechonest.util-module.html#codegen
the method you use has signature
codegen(filename, start=0, duration=30)
so that it is the filename that has to be passed as an argument... not the file itself...
Ex use here http://nullege.com/codes/show/src#p#y#pyechonest-7.1.0#pyechonest#song.py/371/util.codegen
if filename:
if os.path.exists(filename):
query_obj = util.codegen(filename, start=codegen_start, duration=codegen_duration)
if query_obj is None:
raise Exception("The filename specified: %s could not be decoded." % filename)