我刚刚在学习python,这里有一个小问题。我想做的是循环给定的IP地址(192.168.43.215到.218(并运行给定的命令。第一个主机可以连接,而第二个主机(.216(无法连接,然后脚本退出时出现"socket.error:[Erno 111]连接被拒绝"错误。
我不想让它退出脚本,而是继续在剩下的主机上运行。那么,我该如何处理这个异常来保持for循环的运行呢?
#!/usr/bin/python
import socket
import sys
usernames = ["root", "admin", "robot", "email"]
for host in range(215,218):
ipaddress = "192.168.43." + str(host)
print ipaddress
# Create a socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
# Connect to the server
connect=s.connect((ipaddress,25))
# Receieve the banner
banner=s.recv(1024)
print banner
for x in usernames:
# Verify a user
s.send('VRFY ' + x + 'rn')
result=s.recv(1024)
print result
# Close the socket
s.close()
print "All hosts completed."
听起来您只需要使用try/except块进行一些基本的错误处理:
try:
# run dangerous operation
except TheExceptionThatCouldBeTriggered:
print("An exception was triggered... continuing")
else:
# do other stuff if dangerous operation succeeded
在您的情况下,您希望except socket.error