1.

复制代码
"""
修改zabbix导入主机模板
修改后,文档前后添加如下内容
然后导入zabbix web里

<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
    <version>4.0</version>
    <date>2022-02-10T09:48:18Z</date>
    <groups>
        <group>
            <name>华润测试</name>
        </group>
    </groups>
    <hosts>
      *******
    </hosts>
</zabbix_export>

<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
    <version>6.0</version>
    <date>2022-03-17T03:24:26Z</date>
    <groups>
        <group>
            <uuid>a25d9c8527fc443eacfbafd956f86786</uuid>
            <name>华润生产</name>
        </group>
    </groups>
    <hosts>

    </hosts>
</zabbix_export>


"""
def add_zabbix_host(hostname_new,ipaddress_new,file_old,file_new):
    with open(file_old,"r+") as f_old,open(file_new,"a") as f_new:
        lines=f_old.readlines()
        #移动偏移的字节数
        f_old.seek(0)
        for line in lines:
            if "hostname" in line:
               # print(line)
                line=line.replace("hostname",hostname_new)
               # print("new",line)
            if "ipaddress"  in line:
                line=line.replace("ipaddress",ipaddress_new)
            f_new.write(line)
            f_new.write('\n')

#读取hostname,ipaddress
def read_host_ip(hostip_list):
    with open(r"D://wanxiang-hostip.txt",'r') as f:
        lines=f.readlines()
        for line in lines:
            tmp=line.strip('\n').split(" ")
            hostip_list.append(tmp)
    return hostip_list


def main():
    num=0
    hostip_list=[]
    hostip_list=read_host_ip(hostip_list)
    print(hostip_list,len(hostip_list))
    file_old=r"D://wanxiang.xml"
    file_new=r"D://wanxiang_new.xml"
    for hostip in hostip_list:
        add_zabbix_host(hostip[1],hostip[0],file_old,file_new)
        num+=1
    print(num)

if __name__ == '__main__':
    main()
复制代码