将cvs文件发送到Nornir的host.yaml

2024-04-25 14:40:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我不能对同一个问题发表评论,因为共和国信贷不足

我按照@Anthon的建议尝试了yaml cmd,但没有屏蔽所需的输出,也不知道如何从csv代码开始修改yaml,我在“yaml_cmd.py”中查看了代码

任何指导都将不胜感激。正在尝试将大型csv文件转换为hosts.yaml格式以与Nornir一起使用

CSV格式为:

Display-Name,IP-Address,Serial-Number,Machine-Type,IOS-Version,SiteCode2,Group
Device1,1.1.1.1,123456790,Cisco,12.x,Site1,US
Device2,1.1.1.2,123456789,Cisco,13.x,Site2,US

csv输出的Yaml为:

 - "\uFEFFDisplay-Name"
  - IP-Address
  - Serial-Number
  - Machine-Type
  - IOS-Version
  - SiteCode2
  - Product-Edition
  - Product-Version
- - Device1
  - 1.1.1.1
  - 123456790
  - Cisco
  - 12.x
  - Site1
  - US
- - Device2
  - 1.1.1.2
  - 123456789
  - Cisco
  - 13.x
  - Site2
  - US

期望输出为:

Device1:
    hostname: 1.1.1.1
    platform: Cisco
    groups:
        - US
    data:
        site: Site1
        SN: 123456790
        version: 12.x
Device2:
    hostname: 1.1.1.2
    platform: Cisco
    groups:
        - US
    data:
        site: Site2
        SN: 123456789
        version: 13.x

Tags: csv代码nameipcmdyamladdressversion
1条回答
网友
1楼 · 发布于 2024-04-25 14:40:50

嗯,这并不漂亮,但很有效

# Import the csv library
import csv

# Open the sample csv file and print it to screen
with open("test-file.csv") as f:
    print (f.read())

# Open the sample csv file, and create a csv.reader object
with open("test-file.csv") as f:
    csv_2_yaml = csv.reader(f)

    # Loop over each row in csv and leverage the data in yaml
    for row in csv_2_yaml:
        device = row[0]
        ip = row[1]
        SN = row[2]
        platform = row[3]
        version = row[4]
        site = row[5]
        group = row[6]
        print ("{0}:\n    hostname: {1}\n    platform: {2}\n    group:\n        - {3}\n    data:\n        site: {4}\n        SN: {5}\n        version: {6}\n"
        .format(device, ip, platform, group, site, SN, version))

输出为:

Display-Name,IP-Address,Serial-Number,Machine-Type,IOS-Version,SiteCode2,Group
Device1,1.1.1.1,123456790,Cisco,12.x,Site1,US
Device2,1.1.1.2,123456789,Cisco,13.x,Site2,US
Display-Name:
    hostname: IP-Address
    platform: Machine-Type
    group:
        - Group
    data:
        site: SiteCode2
        SN: Serial-Number
        version: IOS-Version

Device1:
    hostname: 1.1.1.1
    platform: Cisco
    group:
        - US
    data:
        site: Site1
        SN: 123456790
        version: 12.x

Device2:
    hostname: 1.1.1.2
    platform: Cisco
    group:
        - US
    data:
        site: Site2
        SN: 123456789
        version: 13.x

相关问题 更多 >