简体   繁体   中英

Python Socket Connection Error/Exception Handling?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM