yum -y install PyYAML
http://www.showyounger.com/show/101586.html
http://pyyaml.org/wiki/PyYAMLDocumentation
yaml.load() 将yaml文档处理为python对象
yaml.dump() 将python对象处理为yaml文档
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import yaml
with file('/tmp/dashboard.yaml', 'r') as f:
content = yaml.load(f)
print content['web']['login'], content['web']['password'], content['interval']
for switch in content['switch']:
print switch['name'], switch['ip'], switch['snmp'], switch['port']
new = {'name': 'bj', 'ip': '192.168.1.100', 'community': 'passwd', 'port': 'GigabitEthernet 0/48', 'bandwidth': 10000}
content['switch'].append(new)
with file('/tmp/dashboard.yaml', 'w') as f:
f.write(yaml.dump(content, indent=4, default_flow_style=False))
# yaml.dump(content, f)
flow_style
interval: 60
switch:
- {ip: 192.168.3.100, name: gz, port: Port-channel 1, community: passwd, bandwidth: 300}
- {ip: 192.168.2.100, name: sh, port: Port-channel 4, community: passwd, bandwidth: 1000}
- {ip: 192.168.1.100, name: bj, port: GigabitEthernet 0/48, community: passwd, bandwidth: 10000}
web: {login: admin, password: 123456}
interval: 60
switch:
- ip: 192.168.3.100
name: gz
port: Port-channel 1
community: passwd
bandwidth: 300
- ip: 192.168.2.100
name: sh
port: Port-channel 4
community: passwd
bandwidth: 1000
- ip: 192.168.1.100
name: bj
port: GigabitEthernet 0/48
community: passwd
bandwidth: 10000
web:
login: admin
password: 123456