您所做的通常被称为“ping 扫描”,并且在谷歌上搜索 PythonPingSweeper 一词时获得了大量点击。
我在网上找到了这个,如果我声称我写了它,我会撒谎,我做了你在旧 DOS Batch 中寻找的东西,但 Python 不是我的事:
如果我违反了在此处附加脚本的一些礼貌规则,那么请默默地抱怨,因为这些人通常会抱怨没有上下文的单行 URL 响应。
https://gist.github.com/4404340
#!/usr/bin/python
import time
import subprocess
import socket
class CannotResolve(Exception):
pass
def resolve(host):
start = time.time()
try:
ip = socket.gethostbyname(host)
except Exception, e:
import traceback
traceback.print_exc()
raise CannotResolve("Cannot resolve %s: %s" % (host, e))
else:
end = time.time()
return (ip, (end-start)*1000)
def ping(host):
cmd = ['ping', '-c', '1', host]
start = time.time()
try:
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
so, se = p.communicate()
except Exception:
# On error, return 0
print "Error running %s" % cmd
print "stderr:\n%s" % se
return 0
else:
end = time.time()
return (end-start)*1000
class Connection(object):
def __init__(self, host, port):
self.host = host
self.port = port
def connect(self):
retries = 10
for x in range(retries):
try:
self.sock = socket.socket()
self.sock.connect( (self.host, self.port) )
except Exception:
import traceback
traceback.print_exc()
print "Retry %s" % (x+1)
time.sleep(1)
else:
return True
print "Giving up after %s attempts" % retries
def send(self, msg):
print "Send: %r" % msg
self.connect()
retries = 10
for x in range(retries):
try:
self.sock.sendall(msg)
except Exception:
import traceback
traceback.print_exc()
print "Retry %s" % (x+1)
time.sleep(1)
else:
return True
print "Giving up after %s attempts" % retries
def main():
delay = 1
hosts = ["google.com", "stackoverflow.com"]
conn = Connection('127.0.0.1', 2003)
while True:
for h in hosts:
now = int(time.time())
hostname = socket.gethostname()
print "Resolving %s" % h
try:
ip, speedms = resolve(h)
except CannotResolve, e:
print "Cannot resolve", e
# Zero values
conn.send(
"pings.%s.dns_%s %s %d\n" % (
hostname, h.replace(".", "_"), 0, now))
conn.send(
"pings.%s.ping_%s %s %d\n" % (
hostname, h.replace(".", "_"), 0, now))
continue # Next host
else:
conn.send(
"pings.%s.dns_%s %s %d\n" % (
hostname, h.replace(".", "_"), speedms, now))
now = int(time.time())
print "Pinging %s (%s)" % (ip, h)
p = ping(h)
print "done"
conn.send(
"pings.%s.ping_%s %s %d\n" % (
hostname, h.replace(".", "_"), p, now))
time.sleep(delay)
if __name__ == '__main__':
main()