Python:将/etc/services文件导入到字典中

4

因此,我需要创建一个Python脚本,导入/etc/services文件并将其写入字典。

目标是将端口/协议作为键,服务作为值。我希望能够打印字典并输入密钥信息,以如下方式返回服务:

print(yourdictionaryname["22/tcp"])
ssh

这个脚本是我能找到的最好的结果。我在网上找到了它,它运行得很好,但它只显示未使用的端口。似乎无法修改它以满足我的需求:

# set the file name depending on the operating system
if sys.platform == 'win32':
file = r'C:\WINDOWS\system32\drivers\etc\services'
else:
file = '/etc/services'

# Create an empty dictionary
ports = dict()

# Iterate through the file, one line at a time
for line in open(file):

# Ignore lines starting with '#' and those containing only whitespace
if line[0:1] != '#' and not line.isspace():

   # Extract the second field (seperated by \s+)
   pp = line.split(None, 1)[1]

   # Extract the port number from port/protocol
   port = pp.split ('/', 1)[0]

   # Convert to int, then store as a dictionary key
   port = int(port)
   ports[port] = None

   # Give up after port 200
   if port > 200: break

# Print any port numbers not present as a dictionary key
for num in xrange(1,201):
if not num in ports:
    print "Unused port", num

听起来这个任务涉及到两个部分:1)将字典写入文件。2)解析该字典文件以获取端口/服务?你卡在哪一步了?首先获取字典(我认为这个脚本已经做到了),并将其写入文件。然后进行第二步。 - chickity china chinese chicken
这个问题的答案如何将字典写入文件?展示了如何将字典(在您发布的脚本中ports是字典)保存到文件中。 - chickity china chinese chicken
2个回答

4

根据你想要实现的目标,socket 模块可能已经足够满足你的需求,它具有 getservbynamegetservbyport 函数:

>>> socket.getservbyport(22)
'ssh'
>>> socket.getservbyport(22, 'udp')
'ssh'
>>> socket.getservbyport(22, 'tcp')
'ssh'
>>> socket.getservbyname('http')
80
>>> socket.getservbyname('http', 'tcp')
80
>>> socket.getservbyname('http', 'udp')
80

如果你确实需要字典,可以使用getservbyport并在range(1, 65536)上进行迭代。


这实际上显示正在运行的服务还是只是常见的服务? - Joe
它为您读取/etc/services。因此,它包含所有已知的服务,而不仅仅是当前正在运行的服务。 - jcomeau_ictx

0

所以我不得不四处寻找才能使这个工作。它是一个很酷的函数。首先它检测操作系统,然后根据/etc/services文件创建字典。接下来它将解析该文件以获取端口输入,然后返回相关的服务。

import sys

# set the file name depending on the operating system
if sys.platform == 'win32':
    file = r'C:\WINDOWS\system32\drivers\etc\services'
else:
    file = '/etc/services'

# Create an empty dictionary
ports = dict()

# Iterate through the file, one line at a time
for line in open(file):

    if line[0:1] != '#' and not line.isspace():
        k = line.split(None, )[1]

        # Extract the port number from port/protocol
        v = line.split('/', )[0]
        j = ''.join([i for i in v if not i.isdigit()])
        l = j.strip('\t')
        ports[k] = l

print(ports.get("22/tcp"))
print(ports.get("8080/tcp"))
print(ports.get("53/udp"))

虽然不常见,但是在除了C:之外的驱动器上安装MS Windows是可能的。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接