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

pdkcd3nj  于 11个月前  发布在  Linux
关注(0)|答案(2)|浏览(119)

所以我必须创建一个python脚本,导入/etc/services文件并将其写入字典。
我们的目标是端口/协议将成为密钥,服务将成为值。我希望能够打印输入密钥信息的dict,并看到服务返回如下:

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

字符串
这个脚本是我能得到的最远的。我在网上找到了它,它工作得很好,但它的设计只是显示未使用的端口。Cant似乎修改它来做我需要的:

# 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

pinkon5k

pinkon5k1#

根据您尝试完成的任务,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

字符串
如果你真的需要这个dict,你可以用getservbyport替换range(1, 65536)

5ktev3wc

5ktev3wc2#

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

import sys
import os

# set the file name depending on the operating system
if sys.platform == 'win32':
    file = os.environ.get('WINDIR', r'C:\WINDOWS') + r'\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"))

字符串

相关问题