如果我們要檢查本地網絡中運行的 Web 服務器,可以使用 Python 的 socket
模塊來進行網絡連接測試。以下是一個簡單的示例代碼,演示如何檢查本地網絡中運行的 Web 服務器:
1、問題背景
在學習如何使用 Python 時,一位用戶希望編寫一段代碼來檢查本地網絡中是否有人運行著 Web 服務器。他們使用提供的代碼遇到了一些錯誤,因此尋求社區的幫助來解決這些問題。
以下錯誤代碼:
#!/usr/bin/env pythonimport 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
2、解決方案
方案 1:使用正確的 Python 語法和錯誤處理
import httplib
import socketfor i in range(1, 256):try:url = "10.1.1.%d" % iconnection = httplib.HTTPConnection(url, 80)connection.request("GET","/")response = connection.getresponse()print url + ":", response.statusexcept socket.error:print url + ":", "error!"
方案 2:使用更 Pythonic 的代碼風格和錯誤處理
import urllib
import threading
import socketdef t_run(thread_list, chunks):t_count = len(thread_list)print("Running %s jobs in groups of %s threads" % (t_count, chunks))for x in range(t_count / chunks + 1):i = x * chunksi_c = min(i + chunks, t_count)c = len([t.start() for t in thread_list[i:i_c]])print("Started %s threads for jobs %s...%s" % (c, i, i_c - 1))c = len([t.join() for t in thread_list[i:i_c]])print("Finished %s threads for job index %s" % (c, i))def url_scan(ip_base, timeout=5):socket.setdefaulttimeout(timeout)def f(url):# print("-- Trying (%s)" % url)try:# the print will only complete if there's a server therer = urllib.urlopen(url)if r:print("## (%s) got %s bytes" % (url, len(r.read())))else:print("## (%s) failed to connect" % url)except IOError, msg:if str(msg)=="[Errno socket error] timed out":returnif str(msg)=="[Errno socket error] (10061, 'Connection refused')":returnprint("## (%s) got error '%s'" % (url, msg))return [threading.Thread(target=f, args=("http://" + ip_base + str(x) + ":" + str(p),)) for x in range(255) for p in [80, 8080]]# run them (increase chunk size depending on your memory)
# also, try different timeouts
t_run(url_scan("209.131.36."), 100)
t_run(url_scan("209.131.36.", 30), 100)
方案 3:修復變量名中的引號
#!/usr/bin/env pythonimport httplib
last = 1
while last <> 255:url = "10.1.1.%d" % lastconnection = httplib.HTTPConnection(url, 80)connection.request("GET","/")response = connection.getresponse()print (response.status)last = last + 1
方案 4:移除引號并使用正確的變量名
#!/usr/bin/env pythonimport httplib
last = 1
while last <> 255:url = "10.1.1." + str(last)connection = httplib.HTTPConnection(url, 80)connection.request("GET","/")response = connection.getresponse()print (response.status)last = last + 1
通過這些解決方案,用戶將能夠準確地檢查本地網絡中是否有運行著的 Web 服務器。
我們可以將 host
參數設置為你想要檢查的主機名或 IP 地址,將 port
參數設置為你所使用的 Web 服務器端口。這樣,你就可以在本地網絡中輕松地檢查 Web 服務器是否運行。是否覺得很方便?如果有任何技術卡殼的問題都可以這里留言討論。