排序ping扫描的Python输出所需的帮助

时间:2016-03-12 13:40:49

标签: python list sorting

我试图对ping扫描的python命令的输出进行排序,并且我看到了一些奇怪的结果。我从另一篇文章中借用了以下内容,该帖子返回了一些未分类的IP地址:

mReactInstanceManager

然后我修改了这个命令: 来自: results_q.put(ip) to: results_q.put(sorted(ip))

#!/usr/bin/python2

import multiprocessing
import subprocess
import os

def pinger( job_q, results_q ):
DEVNULL = open(os.devnull,'w')
while True:
    ip = job_q.get()
    if ip is None: break

    try:
        subprocess.check_call(['ping','-c1',ip],
                              stdout=DEVNULL)
        results_q.put(ip)
    except:
        pass

if __name__ == '__main__':
    pool_size = 55

jobs = multiprocessing.Queue()
results = multiprocessing.Queue()

pool = [ multiprocessing.Process(target=pinger, args=(jobs,results))
         for i in range(pool_size) ]

for p in pool:
    p.start()

for i in range(200,254):
    jobs.put('192.168.1.{0}'.format(i))

for p in pool:
    jobs.put(None)

for p in pool:
    p.join()

while not results.empty():
    ip = results.get()
print(ip)

我期待一个排序列表,但我看到以下内容:

#!/usr/bin/python2

import multiprocessing
import subprocess
import os

def pinger( job_q, results_q ):
DEVNULL = open(os.devnull,'w')
while True:
    ip = job_q.get()
    if ip is None: break

    try:
        subprocess.check_call(['ping','-c1',ip],
                              stdout=DEVNULL)
        results_q.put(sorted(ip))
    except:
        pass

if __name__ == '__main__':
pool_size = 55

jobs = multiprocessing.Queue()
results = multiprocessing.Queue()

pool = [ multiprocessing.Process(target=pinger, args=(jobs,results))
         for i in range(pool_size) ]

for p in pool:
    p.start()

for i in range(200,254):
    jobs.put('192.168.1.{0}'.format(i))

for p in pool:
    jobs.put(None)

for p in pool:
    p.join()

while not results.empty():
    ip = results.get()
print(ip)

关于如何更改以便对返回的实时IP地址列表进行排序的想法,而不是解析每个地址并分解每个地址中包含的字符?

1 个答案:

答案 0 :(得分:0)

将代码的最后一部分更改为:

ips = []
while not results.empty():
    ips.append(results.get())
ips.sort()
for ip in ips:
    print(ip)

这会收集列表中的IP地址,对列表进行排序,然后打印已排序的IP地址。