http检查python

3 python http

在这里学习python,我想检查是否有人在我的本地网络上运行一个Web服务器,使用这个代码,但它在concole中给了我很多错误.

#!/usr/bin/env python

import httplib
last = 1
while last <> 255:
        url = "10.1.1." + "last"
        connection = httplib.HTTPConnection("url", 80)
        connection.request("GET","/")
        response = connection.getresponse()
        print (response.status)
        last = last + 1
Run Code Online (Sandbox Code Playgroud)

ste*_*eha 5

我建议将while循环更改为更惯用的for循环,并处理异常:

#!/usr/bin/env python

import httplib
import socket


for i in range(1, 256):
    try:
        url = "10.1.1.%d" % i
        connection = httplib.HTTPConnection(url, 80)
        connection.request("GET","/")
        response = connection.getresponse()
        print url + ":", response.status
    except socket.error:
        print url + ":", "error!"
Run Code Online (Sandbox Code Playgroud)

要查看如何为此添加超时,因此检查每个服务器不需要这么长时间,请参阅此处.