0

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'
5
  • just catching SocketError, add catch statement for ConnectionResetError -- examples-wiki Commented Jun 10, 2014 at 16:03
  • Ok see updated code, I tried a connectionreseterror but is that a part of telnet or socket? Commented Jun 10, 2014 at 16:05
  • @user3570335, I think I need a winerror, but when trying to catch a winerror I get: TypeError: catching classes that do not inherit from BaseException is not allowed Commented Jun 10, 2014 at 16:13
  • try except socket.error, e: print "Ohhh socket error" Commented Jun 10, 2014 at 19:17
  • Oh ok that didn't work but using a generic one was, so Exception as e seems to have worked. Commented Jun 10, 2014 at 20:22

1 Answer 1

1

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 = '?'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.