[Python] YAML implementation in Python help, 2 weeks beginner

Discussão em 'Python' iniciado por Stack, Maio 31, 2025.

  1. Stack

    Stack Membro Participativo

    I made this Python script so its faster to edit Netplan YAML files, but for some reason it gives more errors than enything, and it doesn't netplan apply for some reason, please explain as much as you want I want to learn from this. I am using Ubuntu 24.04, and python3. thanks in advance!. I dont know what to write more but its asking me to write more details so.... I like dogs.... 2+2 is 4.... num1 = input("introduce a number:") num2= input("introduce a secund number") print(f{num1} + {num2} = {num1+num2})

    import os
    import subprocess
    import yaml

    #Welcoming banner
    print("---------- NETPLANCHANGER ----------")
    netplan_folder = "/etc/netplan"

    def CheckIfRoot():
    #Verifies root perms
    if os.getuid() != 0:
    print("You need to run this script as root")
    exit(1)

    def SelectYAML(netplandir):
    #List of options
    netplanoptions = [f for f in os.listdir(netplandir) if f.endswith(('.yaml', '.yml'))]
    print(netplanoptions)
    while True:
    SELECT_NETPLAN = input("What file do you want to edit?: ")
    if SELECT_NETPLAN in netplanoptions:
    return SELECT_NETPLAN
    else:
    print("File not valid.\n")



    def ContentNBackup(netplandir, SELECT_NETPLAN):
    try:
    #Paths
    absolutepath = os.path.join(netplandir, SELECT_NETPLAN)
    absolutebackup = absolutepath + ".bak"

    #Open .yaml/.yml
    with open(absolutepath, 'r') as file:
    print("\nFile content:")
    print("----------------------------------")
    print(file.read())

    with open(absolutebackup, 'w') as file:
    netplanabierto = open(absolutepath, 'r').read()
    file.write(netplanabierto)
    print("----------------------------------")
    print(f"Backup of {SELECT_NETPLAN} in {absolutebackup}")
    return absolutepath

    except FileNotFoundError:
    print("File not found")


    def OpenYAML(absolutepath):
    #Open YAML file and loads it
    with open(absolutepath, 'r') as file:
    Data = yaml.safe_load(file)
    return Data


    def SelectIF(yamldata):
    #Interface selection
    try:
    print("\n")
    result = subprocess.run(['ip', '-o', 'link', 'show'], capture_output=True, text=True)
    interfaces = []
    for line in result.stdout.splitlines():
    iface = line.split(': ')[1].split('@')[0]
    if iface != "lo":
    interfaces.append(iface)
    print(iface)

    while True:
    Interface = input("Select the interface you want to edit: ")
    if Interface not in interfaces:
    print("Select a valid interface")
    continue
    else:
    break
    except Exception as e:
    print(f"Error selecting the interface {e}")
    exit(1)

    return Interface


    def NetplanNewEntries(yamldata, interface):
    #Creates new entries in YAML file
    dhcp = input("Do you want to use DHCP (y/n)?: ").lower()
    while dhcp not in ['y', 'n']:
    print("Please enter 'y' or 'n'.")
    dhcp = input("Do you want to use DHCP (y/n)?: ").lower()

    if 'network' not in yamldata:
    yamldata['network'] = {}

    if 'ethernets' not in yamldata['network']:
    yamldata['network']['ethernets'] = {}

    if interface not in yamldata['network']['ethernets']:
    yamldata['network']['ethernets'][interface] = {}

    if dhcp == "n":
    yamldata['network']['ethernets'][interface]['dhcp4'] = False
    if 'addresses' not in yamldata['network']['ethernets'][interface]:
    yamldata['network']['ethernets'][interface]['addresses'] = []
    if 'nameservers' not in yamldata['network']['ethernets'][interface]:
    yamldata['network']['ethernets'][interface]['nameservers'] = {"addresses": []}
    if 'gateway4' not in yamldata['network']['ethernets'][interface]:
    yamldata['network']['ethernets'][interface]['gateway4'] = ""
    else: # dhcp == "y"
    yamldata['network']['ethernets'][interface]['dhcp4'] = True

    return dhcp



    def UserConfig():
    #User inputs for config
    ip = input("New IP Address in CIDR formar (ej 192.168.1.10/24): ")
    gateway = input("Gateway (ej: 192.168.1.1): ")
    dns_raw = input("DNS separated by comma (ej: 8.8.8.8,4.4.4.4)")
    dns = [d.strip() for d in dns_raw.split(",")]
    return ip, gateway, dns


    def NetplanMod(interface, dhcp, ip, gateway, dns, yamldata):
    #Modifying YAML
    if dhcp == "y":
    return

    if dhcp == "n":
    yamldata['network']['ethernets'][interface]['addresses'] = [ip]
    yamldata['network']['ethernets'][interface]['gateway4'] = gateway
    yamldata['network']['ethernets'][interface]['nameservers'] = {"addresses": dns}
    return

    def SaveYAML(yamlpath, yamldata):
    #Saving YAML
    print("New YAML content:\n")
    print("-------------------")
    print(yaml.dump(yamldata, default_flow_style=False))
    with open(yamlpath, 'w') as file:
    yaml.dump(yamldata, file, default_flow_style=False)
    print(f"Netplan saved to {yamlpath}.")

    def ApplyNetplan():
    #Aplies netplan
    try:
    result = subprocess.run(['netplan', 'apply'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print("Netplan applied successfully.")
    except subprocess.CalledProcessError as e:
    print("Error applying Netplan: ")
    print(e.stderr.decode())


    def Main():
    #Main function
    CheckIfRoot()

    selectednetplan = SelectYAML(netplan_folder)

    YAMLAbsolutePath = ContentNBackup(netplan_folder, selectednetplan)

    YAMLData = OpenYAML(YAMLAbsolutePath)

    UserInterface = SelectIF(YAMLData)

    UserDHCP = NetplanNewEntries(YAMLData, UserInterface)

    if UserDHCP == "n":
    UserIP, UserGateway, UserDNS = UserConfig()
    NetplanMod(UserInterface, UserDHCP, UserIP, UserGateway, UserDNS, YAMLData)

    else:
    print("DHCP selected, skipping IP/Gateway/DNS input.")

    SaveYAML(YAMLAbsolutePath, YAMLData)

    ApplyNetplan()

    return

    Main()

    Continue reading...

Compartilhe esta Página