所以我有下面的循环,它可以很好地工作,直到它遇到某些只会导致连接错误的主机。不幸的是,它不是跳过这些实例,而是导致脚本崩溃。我知道要抓住并避免这种异常,最好在try:except块中通过令人不安的声明(serveroutput = tn.read_until(b' STARTTLS'))。我可以这样做,但是我不知道如何捕捉错误并告诉它继续前进。如果我添加一个中断,它将打破循环并导致脚本过早停止。我怎样才能继续迭代j?我听说我可以继续使用'作为一种继续迭代的方法,但我甚至在这里捕捉到了正确的异常吗?
我的代码:
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'
答案 0 :(得分:1)
最终为我工作的是对@ user3570335建议的修改。
try:
serveroutput = tn.read_until(b'STARTTLS')
except Exception as e:
tlsbool = '?'