我只是在学习python,而我对此毫无疑问。我想要做的是循环给定的IP地址(192.168.43.215至.218)并运行给定的命令。第一个主机可以连接,而第二个主机(.216)无法连接,然后脚本退出,并显示“ socket.error:[Errno 111] Connection拒绝”错误。
我不希望它退出脚本,而是继续在其余主机上运行。那么,如何处理此异常以保持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 + '\r\n')
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句