Search code examples
pythonlinuxdictionaryformat

Python: Import /etc/services file to a Dictionary


So I have to create a python script that will import /etc/services file and write it to a dictionary.

The goal is that the port/protocol will become the key and service the value. I want to be able to print the dict entering the key info and see the service return as such:

print(yourdictionaryname["22/tcp"])
ssh

This script is the furthest I have been able to get. I found it online and it works great but it is designed to just show unused ports. Cant seem to modify it to do what i need:

# 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

Solution

  • So I had to look all around to get this to work. It is a cool function. First it detects the OS then it creates a dictionary based on the /etc/services file. Next it will parse that file for port input then return the associated service.

    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"))