Home > front end >  How can I add manual input from user in YAML file using python?
How can I add manual input from user in YAML file using python?

Time:06-23

I want to take input from user and add it in YAML file.

I'm trying making a script which asks user if they want to add new interface information or change existing interface information. The YAML file which I want to edit and update:

network:
  version: 2
  renderer: networkd
  ethernets:
    enx1:
      addresses:
      - 193.254.1.6/24
      nameservers:
          addresses: [193.254.1.5, 8.8.8.8]
      routes:
          - to: 193.254.1.0/24
            via: 193.254.1.5

I want that the user input values will add in the existing file and create a new interface entry

    #!/bin/sh
    import ruamel.yaml

yml = ruamel.yaml.YAML()

print("Do u want to add new routes")
resp = input("Yes or No \n")
if resp.lower() == "yes":
    with open('/etc/netplan/01-network-manager-all.yaml') as fp:
        cont = yml.load(fp)
        print(cont)
    eth = input("Enter interface name \n")
    addr = input("Enter IP address and mask. e.g., 8.8.8.8/8 \n")
    dns = input("Enter DNS \n")
    rts = input("Enter routes -to \n")
    rts1 = input("Enter routes via \n")
    yml_s = """\
    network:
      version: 2
      renderer: networkd
      ethernets:
        :
          addresses:
          - 193.254.1.8/24
          nameservers:
              addresses: [193.254.1.5, 8.8.8.8]
          routes:
              - to: 193.254.1.0/24
                via: 193.254.1.5
    """
else:
    pass

CodePudding user response:

From the answers that you get you should create a data structure, something like the following after the last line with input(...):

new_ethernet = {eth: dict(
    addresses=[addr], 
    nameservers=dict(addresses=[x.strip() for x dns.split(',')]),
    routes=[dict(to=rts, via=rts1)]

( I would put that into a function together the input code and give an option that will not ask the input, but set some default values, that make it easy to test without having to input values every time)

After that load the original file, optionally check if eth is already there and get confirmation before overwriting and save back to file:

from pathlib import Path
import ruamel.yaml
ethernet_info_file = Path('ethernet.yaml')


yaml = ruamel.yaml.YAML()
data = yaml.load(ethernet_info_file)
if dns in data['network']['ethernets']:
    if not confirm_to_overwrite():
        return
data['networks'['ethernets'].update(new_ethernet)
yaml.dump(data, ethernet_info_file)

CodePudding user response:

I tried this code

import ruamel.yaml
import os.path

eth_file = os.path.join("etc","netplan","01-network-manager-all.yaml")
yml = ruamel.yaml.YAML()
data = yml.load(eth_file)

print("Do u want to change new routes")
resp = input("Yes or No \n")
if resp.lower() == "yes":

    eth = input("Enter interface name \n")
    addr = input("Enter IP address and mask. e.g., 8.8.8.8/8 \n")
    dns = input("Enter DNS \n")
    rts = input("Enter routes -to \n")
    rts1 = input("Enter routes via \n")
    new_ether = {eth: dict(
        addresses=[addr],
        nameservers=dict(addresses=[x.strip() for x in dns.split(',')]),
        routes=[dict(to=rts, via=rts1)]
    )}

    if dns in data['network']['ethernets']:
        if not confirm_to_overwrite():
            quit()
    data['network']['ethernets'].update(new_ether)
    yaml.dump(data, eth_file)
else:
   pass

And got the below error

Traceback (most recent call last):
    File "/home/sipl/PycharmProjects/pyScr/venv/ymlscr_1.py", line 27, in <module>
    if 'dns' in data['network']['ethernets']:
TypeError: string indices must be integers
  • Related