Skip to content

Instantly share code, notes, and snippets.

@TTTPOB
Last active March 28, 2024 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TTTPOB/7f94025979227bec06b24ec49ca71df5 to your computer and use it in GitHub Desktop.
Save TTTPOB/7f94025979227bec06b24ec49ca71df5 to your computer and use it in GitHub Desktop.
see name
#!/usr/bin/env python3
import os
import re
def parse_podman_service(service_content):
result = {"name": None, "ip": None}
if not re.search(r'^ExecStart=(/usr/bin/podman|podman)\s', service_content, re.MULTILINE):
return result
ip_match = re.search(r'--ip(\s+|=)(\d+\.\d+\.\d+\.\d+)', service_content)
name_match = re.search(r'(?:--name|-n)(\s+|=)([\w-]+)', service_content)
if ip_match:
result["ip"] = ip_match.group(2)
if name_match:
result["name"] = name_match.group(2)
return result
def update_hosts_section(hosts_path, section_name, entries):
section_start = f"# BEGIN {section_name}"
section_end = f"# END {section_name}"
new_section = [section_start] + [f"{ip} {name}" for ip, name in entries if ip and name] + [section_end]
try:
with open(hosts_path, 'r') as file:
lines = file.readlines()
if lines[-1][-1] != '\n':
lines.append('\n')
start_index = end_index = -1
start_found = end_found = False
for i, line in enumerate(lines):
if line.strip() == section_start:
start_index = i
start_found = True
elif line.strip() == section_end:
end_index = i
if start_found:
end_found = True
if start_found and end_found:
break
if start_index != -1 and end_index != -1:
lines[start_index:end_index + 1] = []
lines.extend([line + '\n' for line in new_section])
with open(hosts_path, 'w') as file:
file.writelines(lines)
except IOError as e:
print(f"Error updating hosts file: {e}")
return False
return True
def scan_and_update_hosts(service_dir, hosts_path):
entries = []
for filename in os.listdir(service_dir):
if filename.endswith('.service'):
fp = os.path.join(service_dir, filename)
if not os.path.exists(fp):
continue
with open(fp, 'r') as file:
service_content = file.read()
service_info = parse_podman_service(service_content)
if service_info['name'] and service_info['ip']:
entries.append((service_info['ip'], service_info['name']))
entries.insert(0, ("10.88.0.1", "podman-host"))
return update_hosts_section(hosts_path, 'podman-service-hosts', entries)
if __name__ == '__main__':
# Example usage
service_dir = '/etc/systemd/system' # Replace with your service directory path
hosts_path = '/etc/hosts' # Replace with your hosts file path for testing
scan_and_update_hosts(service_dir, hosts_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment