如何用端口号对IP地址排序?

时间:2019-08-06 09:03:43

标签: python sorting ip

我正在创建自己的报告工具,并且试图弄清楚如何用端口号对IP地址进行排序。

如何对具有端口号的IP地址进行排序,以便先对IP地址进行排序,然后再对端口号进行排序。我可以对IP地址进行排序,但是当与端口号结合使用时,会变得很困难。

a = ['192.168.0.3 (443/tcp)|', '192.168.0.176 (443/tcp)|', '192.168.0.40 (443/tcp)|', '192.168.0.15 (8443/tcp)|', '192.168.0.16 (8443/tcp)|', '192.168.0.12 (443/tcp)|', '192.168.0.9 (3389/tcp)|', '192.168.0.15 (443/tcp)|', '192.168.0.16 (443/tcp)|', '192.168.0.3 (3389/tcp)|', '192.168.0.14 (443/tcp)|']

print(a.sort(key=lambda s: map(int, s.split('.')))) #this works fine with just IP address not with the current format of (xxx/tcp). The pipe is for delimiters so please ignore.

我想先按IP地址对输出进行排序,然后再对每个IP通过端口号进行排序。因此,例如,前几个结果将是:

a= ['192.168.0.3 (443/tcp)|', '192.168.0.3 (3389/tcp)|', 192.168.0.9 (3389/tcp)|, ...']

3 个答案:

答案 0 :(得分:4)

使用re.findall

import re

def get_ip_port(x):
    *ips, port = map(int, re.findall('\d+', x))
    return ips, port

sorted(a, key=get_ip_port)

输出:

['192.168.0.3 (443/tcp)|',
 '192.168.0.3 (3389/tcp)|',
 '192.168.0.9 (3389/tcp)|',
 '192.168.0.12 (443/tcp)|',
 '192.168.0.14 (443/tcp)|',
 '192.168.0.15 (443/tcp)|',
 '192.168.0.15 (8443/tcp)|',
 '192.168.0.16 (443/tcp)|',
 '192.168.0.16 (8443/tcp)|',
 '192.168.0.40 (443/tcp)|',
 '192.168.0.176 (443/tcp)|']

说明:

  • map(int, re.findall('\d+', x)):查找所有数字并将其设为int
  • *ips, port:解压缩以上int个文件并重新打包成除最后一个(*ips)和最后一个(port)之外的所有文件
  • sorted(a, key=get_ip_port):当get_ip_port返回两个键(ipsport)时,sorted首先将a排序为{{1} },然后根据需要ips

答案 1 :(得分:0)

您可以使用多个条件(以map(int,e[0].split('.'))作为条件1,以int(e[1].lstrip('(').split('/')[0])作为条件2)进行排序,如下所示,

>>> a
['192.168.0.3 (443/tcp)|',
 '192.168.0.176 (443/tcp)|',
 '192.168.0.40 (443/tcp)|',
 '192.168.0.15 (8443/tcp)|',
 '192.168.0.16 (8443/tcp)|',
 '192.168.0.12 (443/tcp)|',
 '192.168.0.9 (3389/tcp)|',
 '192.168.0.15 (443/tcp)|',
 '192.168.0.16 (443/tcp)|',
 '192.168.0.3 (3389/tcp)|',
 '192.168.0.14 (443/tcp)|']
>>> [i.split() for i in a]
[['192.168.0.3', '(443/tcp)|'],
 ['192.168.0.176', '(443/tcp)|'],
 ['192.168.0.40', '(443/tcp)|'],
 ['192.168.0.15', '(8443/tcp)|'],
 ['192.168.0.16', '(8443/tcp)|'],
 ['192.168.0.12', '(443/tcp)|'],
 ['192.168.0.9', '(3389/tcp)|'],
 ['192.168.0.15', '(443/tcp)|'],
 ['192.168.0.16', '(443/tcp)|'],
 ['192.168.0.3', '(3389/tcp)|'],
 ['192.168.0.14', '(443/tcp)|']]

>>> sorted([i.split() for i in a],key=lambda e: (map(int,e[0].split('.')),int(e[1].strip('(').split('/')[0])))
[['192.168.0.3', '(443/tcp)|'],
 ['192.168.0.3', '(3389/tcp)|'],
 ['192.168.0.9', '(3389/tcp)|'],
 ['192.168.0.12', '(443/tcp)|'],
 ['192.168.0.14', '(443/tcp)|'],
 ['192.168.0.15', '(443/tcp)|'],
 ['192.168.0.15', '(8443/tcp)|'],
 ['192.168.0.16', '(443/tcp)|'],
 ['192.168.0.16', '(8443/tcp)|'],
 ['192.168.0.40', '(443/tcp)|'],
 ['192.168.0.176', '(443/tcp)|']]

答案 2 :(得分:0)

您可以使用sorted在一行中完成此操作,如下所示:

sorted(a, key=lambda x:x.split(' ')[0])