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

2024-05-14 03:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在学习python,我有一个noobquestion。我要做的是循环给定的IP地址(192.168.43.215到.218)并运行给定的命令。第一个主机可以正常连接,而第二个(.216)无法连接到,然后脚本将以一个“套接字错误:[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."

Tags: theinimport脚本hostforconnect错误
1条回答
网友
1楼 · 发布于 2024-05-14 03:27:53

听起来您只需要对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

相关问题 更多 >