gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:17:34 25 4
gpt4 key购买 nike

所以我必须创建一个 python 脚本来导入 /etc/services 文件并将其写入字典。

目标是端口/协议(protocol)将成为键,服务成为值。我希望能够打印输入关键信息的字典并查看服务返回结果:

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

最佳答案

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

关于Python:将/etc/services 文件导入字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com