python-scapy: how to translate port numbers to service names?

微笑、不失礼 提交于 2019-12-24 06:30:47

问题


A TCP layer in Scapy contains source port:

>>> a[TCP].sport
80

Is there a simple way to convert port number to service name? I've seen Scapy has TCP_SERVICES and UDP_SERVICES to translate port number, but

print TCP_SERVICES[80] # fails
print TCP_SERVICES['80'] # fails
print TCP_SERVICES.__getitem__(80) # fails
print TCP_SERVICES['www'] # works, but it's not what i need
80

Someone know how can I map ports to services?

Thank you in advance


回答1:


If this is something you need to do frequently, you can create a reverse mapping of TCP_SERVICES:

>>> TCP_REVERSE = dict((TCP_SERVICES[k], k) for k in TCP_SERVICES.keys())
>>> TCP_REVERSE[80]
'www'



回答2:


Python's socket module will do that:

>>> import socket
>>> socket.getservbyport(80)
'http'
>>> socket.getservbyport(21)
'ftp'
>>> socket.getservbyport(53, 'udp')
'domain'



回答3:


This may work for you (filtering the dictionary based on the value):

>>> [k for k, v in TCP_SERVICES.iteritems() if v == 80][0]
'www'



回答4:


If you are using unix or linux there is a file /etc/services which contains this mapping.




回答5:


I've found a good solution filling another dict self.MYTCP_SERVICES

for p in scapy.data.TCP_SERVICES.keys():
  self.MYTCP_SERVICES[scapy.data.TCP_SERVICES[p]] = p 


来源:https://stackoverflow.com/questions/976599/python-scapy-how-to-translate-port-numbers-to-service-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!