如何处理socket"连接拒绝" Python中的异常?

时间:2015-07-03 06:07:58

标签: python

我刚刚学习python而且我在这里没有任何想法。我想要做的是循环给定的IP地址(192.168.43.215到.218)并运行给定的命令。第一个主机可以连接,而第二个(.216)无法连接,然后脚本以" socket.error退出:[Errno 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 + '\r\n')
                result=s.recv(1024)
                print result
                # Close the socket

        s.close()

print "All hosts completed."

1 个答案:

答案 0 :(得分:1)

听起来你需要使用try/except块进行一些基本的错误处理:

.wrap {
  word-spacing: 3em;
  padding: 1em 0 0;
}
.module {
  background: lightsteelblue;
  height: 5em;
  width: 5em;
  display: inline-block;
  /* reset word-spacing so that text inside this box is spaced normally */
  word-spacing: normal;
}

在您的情况下,您想要try: # run dangerous operation except TheExceptionThatCouldBeTriggered: print("An exception was triggered... continuing") else: # do other stuff if dangerous operation succeeded

相关问题