[英]Python Socket Connection Error/Exception Handling?
因此,我使用下面的循环效果很好,直到它碰到某些仅会导致连接错误的主机。 不幸的是,它没有跳过这些实例,而是导致脚本崩溃。 我知道要捕获并避免此异常,最好是在try:except块中通过麻烦的语句(serveroutput = tn.read_until(b'STARTTLS')) 。 我可以做到,但是我不确定如何捕获错误并告诉它继续进行。 如果添加一个中断,它将中断循环并导致脚本无论如何都提前停止。 我如何继续遍历j? 我听说我可以使用“ continue”作为继续迭代的方法,但是我是否在这里捕捉到了正确的异常?
我的代码:
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:
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.
全栈错误:
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
更新:
我尝试了以下代码,但收到以下错误。
代码:尝试:serveroutput = tn.read_until(b'STARTTLS'),除了tn.ConnectionsResetError:继续
错误:
AttributeError: 'Telnet' object has no attribute 'ConnectionsResetError'
最终对我有用的是对@ user3570335建议的修改。
try:
serveroutput = tn.read_until(b'STARTTLS')
except Exception as e:
tlsbool = '?'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.