Advertisement
Nenogzar

sort_protokol_in_server_file.py

Mar 17th, 2024
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. import re
  2.  
  3. # Пътят към файла, който трябва да се обработи
  4. file_path = r'C:\Windows\System32\drivers\etc\services'
  5.  
  6. # Прочитане на данните от файла
  7. with open(file_path, 'r') as file:
  8.     data = file.read()
  9.  
  10. # Дефиниране на регулярния израз
  11. pattern = re.compile(r'(?P<service>\S+)\s+(?P<port>\d+)/(?P<protocol>\S+)\s+(?P<aliases>.*?)(?:\s+#(?P<comment>.*))?\n')
  12.  
  13. # Извличане на данните с регулярния израз
  14. matches = pattern.finditer(data)
  15.  
  16. # Създаване на списък за съхранение на данните
  17. services = []
  18.  
  19.  
  20. # Парсиране на данните и добавяне към списъка
  21. for match in matches:
  22.     service = match.group('service')
  23.     port = match.group('port')
  24.     protocol = match.group('protocol')
  25.     aliases = match.group('aliases').strip().split()
  26.     comment = match.group('comment')
  27.     services.append({'service': service, 'port': port, 'protocol': protocol, 'aliases': aliases, 'comment': comment})
  28.  
  29. # Сортиране на данните по протокол и порт
  30. sorted_services = sorted(services, key=lambda x: (x['protocol'], int(x['port'])))
  31. # Сортиране на данните по aliases
  32. sorted_by_aliases = sorted(services, key=lambda x: x['aliases'])
  33.  
  34. # Пътят за записване на файла със сортираните данни
  35. output_file_path = r'sorted_services.txt'
  36. output_file_path1 = r'sorted_services_by_aliases.txt'
  37.  
  38. # Записване на сортираните данни в текстов файл
  39. with open(output_file_path, 'w') as output_file:
  40.     for service in sorted_services:
  41.         output_file.write(f"{service['protocol']} : {service['port']} - {service['service']}, aliases - {', '.join(service['aliases'])} - {service['comment']}\n")
  42.  
  43. with open(output_file_path1, 'w') as output_file:
  44.     for service in sorted_by_aliases:
  45.         output_file.write(f"{service['protocol']} : {service['port']} - {service['service']}, aliases - {', '.join(service['aliases'])} - {service['comment']}\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement