所以我必须创建一个 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
根据您想要完成的任务,socket模块可能足以满足您的需求,其
getservbyname
和getservbyport
功能:
>>> 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
如果你确实需要字典,你可以用
range(1, 65536)
迭代 getservbyport
。
所以我必须四处寻找才能让它发挥作用。这是一个很酷的功能。首先它检测操作系统,然后根据 /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"))