How to Get all Ip and Mac address from the yml file in python?

Viewed 108
EthernetClient:
     Windows:    
        ip: 192.168.1.152
        mac_adr: ‘X4:81:C7:BD:46:04'

     Windows_Extnd:    
        ip: 192.168.1.151
        mac_adr: 'X4:81:C7:BD:47:04'
        
WifiClient:
    Windows:    
        ip: 192.168.1.154
        mac_adr: 'X4:81:C7:BD:47:05’
    MAC:    
        ip: 192.168.1.3
        mac_adr: 'X4:81:C7:BD:47:06’
        
    IOS:    
        ip: 192.168.1.4
        mac_adr: 'X4:81:C7:BD:47:07’

This was the Yml file. From which i need to get ip and mac_adr for all keys. I reached upto get the all data

import yaml
a_yaml_file = open("../Test/example.yml")
parsed_yaml_file = yaml.load(a_yaml_file, Loader=yaml.FullLoader)

print(parsed_yaml_file["EthernetClient"])
print(parsed_yaml_file.get("WifiClient"))
1 Answers

There's some issues with you .yml file

  • There's spacing at your last line mac_adr: 'X4:81:C7:BD:47:07’
  • You started with ' but end with `

test.yml

EthernetClient:
  Windows:    
    ip: 192.168.1.152
    mac_adr: ‘X4:81:C7:BD:46:04'
  Windows_Extnd:    
    ip: 192.168.1.151
    mac_adr: 'X4:81:C7:BD:47:04'

WifiClient:
  Windows:    
      ip: 192.168.1.154
      mac_adr: 'X4:81:C7:BD:47:05'
  MAC:
      ip: 192.168.1.3
      mac_adr: 'X4:81:C7:BD:47:06'
  IOS:    
      ip: 192.168.1.4
      mac_adr: 'X4:81:C7:BD:47:07'

ExecutionScript.py

import yaml

with open("test.yml", 'r') as f:
    valuesYaml = yaml.load(f, Loader=yaml.FullLoader)
    print(valuesYaml["EthernetClient"])
    print(valuesYaml.get("WifiClient"))

Finally here's how you get the value


As per requested, below's how you get the full list of IP

import yaml

with open("test.yml", 'r') as f:
    listOfIp = []
    valuesYaml = yaml.load(f, Loader=yaml.FullLoader)
    
    for clientType, clientValues in valuesYaml.items():
        for attr, value in clientValues.items():
            if 'ip' in value:
                listOfIp.append(value['ip'])

print(listOfIp) # ['192.168.1.152', '192.168.1.151', '192.168.1.154', '192.168.1.3', '192.168.1.4']
Related