从configparser中加入类似的部分

问题描述 投票:0回答:1

早上好,

我有一个配置文件,其中包含这样的数据:

[hostset 1]
ip = 192.168.122.136
user = test
password =
pkey = ~/.ssh/id_rsa

[hostset 2]
ip = 192.168.122.138
user = test
password =
pkey = ~/.ssh/id_rsa

如果其他值相同,我希望能够在此配置文件中加入任意给定数量的主机集的ips,因此,所提取和格式化的数据将存储在dict中,如下所示:

{
 ip: ['192.168.122.136', '192.168.122.138'],
 user: 'test',
 password: '',
 pkey: '~/.ssh/id_rsa',
}

有人有这样做的聪明方法吗?

python python-3.x ini
1个回答
0
投票

在此解决方案中,我假定文件格式与问题中所述的完全相同:首先,我们拆分主机集:我们假设您的数据在rowdata变量中

HostSets = rowdata.split("[hostset ") # first element is empty
Dict = {}

for i in range (1,len(HostSets)):
    l = HostSets[i].split("ip = ")#two elements the first is trash
    ip = l[1].split()[0]
    conf =l[1].split("\n",1 )[1] #splits only the first element 
    try :
        Dict[conf].append(ip)
    except :
        Dict[conf] = list()
        Dict[conf].append(ip)        
print('{')
for element in Dict:
    print("ip: ",Dict[element],",",element)
print('}')
© www.soinside.com 2019 - 2024. All rights reserved.