问题
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