你正在做的事通常被稱爲「ping掃描」,GooglePingSweeper這個詞的谷歌搜索以大量的點擊回來。
我發現這個網上,我想,如果我要求我寫的是在說謊,我做你要找什麼在老的DOS批處理但是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()
感謝輸入,但pingsweep是不是我想要的。如果我嘗試發現在線主機,服務等,我會利用pingings。我不是,我已經有一個csv文件中的設備列表。我需要將這一切以相同格式輸出到csv文件,並將主機名替換爲相應的IP,同時保留已經單獨列出的IP。 – Marq
問題,你是否反對使用for/if命令來完成它?假設你的行有奇偶校驗,並且兩行文件中#8433行相同,並且所有數據都放在同一列中,你可能已經知道你可以在一行或更少行的命令行中執行此操作。 – HopeItHelps