在这里学习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
答案 0 :(得分: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!"
要了解如何为此添加超时,因此检查每台服务器的时间不会太长,请参阅here。
答案 1 :(得分:2)
正如所指出的,你有一些基本的 报价问题。但更根本的是:
顺便说一句,我正在打印返回网页的大小,因为它很简单 页面的“签名”。样本IP返回各种Yahoo 资产。
import urllib
import threading
import socket
def 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 * chunks
i_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 there
r = urllib.urlopen(url)
if r:
print "## (%s) got %s bytes" % (url, len(r.read()))
else:
print "## (%s) failed to connect" % url
except IOError, msg:
# these are just the common cases
if str(msg)=="[Errno socket error] timed out":
return
if str(msg)=="[Errno socket error] (10061, 'Connection refused')":
return
print "## (%s) got error '%s'" % (url, msg)
# you might want 8000 and 8001, too
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)
答案 2 :(得分:1)
从变量名称last
和url
中删除引号。 Python将它们解释为字符串而不是变量。试试这个:
#!/usr/bin/env python
import httplib
last = 1
while last <> 255:
url = "10.1.1.%d" % last
connection = httplib.HTTPConnection(url, 80)
connection.request("GET","/")
response = connection.getresponse()
print (response.status)
last = last + 1
答案 3 :(得分:1)
您正在尝试连接到字面上字符串'url'
的网址:这就是您在
connection = httplib.HTTPConnection("url", 80)
<强>意味着即可。一旦你解决了这个问题(通过删除那些引号),你将尝试连接到“10.1.1.last”,给出上一个行中的引号。将该行设置为
url = "10.1.1." + str(last)
它可以工作! - )