因此,我需要创建一个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
ports
是字典)保存到文件中。 - chickity china chinese chicken