我写了一个这样的python脚本:
#!/usr/bin/python
import sys
import requests
if len(sys.argv) != 2:
print "Usage: python %s <IP-LIST>" % (sys.argv[0])
sys.exit();
InputFile = sys.argv[1]
try:
File = open(InputFile)
for ip in File:
IP = ip.rstrip()
out = requests.get("http://" + IP, timeout=5)
out.status_code
except (KeyboardInterrupt, SystemExit):
print "nKeyboardInterruption with Ctrl+c signal"
except IOError as e:
print "The file "%s" does not exist!" % (sys.argv[1])
当url没有任何响应时,显示以下输出:
The file "list.txt" does not exist!
为什么?
requests
使用子类IOError
的异常,您正在捕获并假设未找到文件。如果你使用Python 3,你可以捕获更具体的FileNotFoundError
。在这里,您应该将except requests.RequestException
块放在except IOError
块之上(或者如果您愿意,将其分解为特定的requests
错误)。