Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
9.6 kB
4
Indexable
Never
import os
import paramiko
from paramiko import sftp
from paramiko.ssh_exception import SSHException
from paramiko import AuthenticationException
from logging import error
from proxmoxer import ProxmoxAPI
from proxmoxer import ResourceException
import xml.etree.ElementTree as ET
host = 'fw.dev.mono.info.tr'
username = 'root'
password = None
remote_file_path = '/conf/config.xml'
local_path = '/home/omertaha/Desktop/Python/config.xml'
source_path = '/home/omertaha/Desktop/Python/edited.xml'
destination_path = '/conf/test.xml'
try:
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host,username=username,password=password)
    print("Successful SSH Connection to {0} with {1}".format(host,username))
except AuthenticationException:
    print("Authentication Error")
except SSHException:
    print("SSH Connection Error")
try:
    sftp = ssh.open_sftp()
    sftp.get(remote_file_path,local_path)
    print("Getting file is successful")
    print("File Location is: {0}".format(local_path))
except IOError:
    print("Getting File Errored")
tree=ET.parse('/home/omertaha/Desktop/Python/config.xml')
root = tree.getroot()
count = 0
proxmox = ProxmoxAPI('lab1.monocloud.com.tr', user='api@pve',
                     password='YG22YEZdqX69FGan4cTnq7AcfrAdXZGW', verify_ssl=False,service='PVE')
for node in proxmox.nodes.get():
    for qemu in proxmox.nodes.get(f"{node['node']}/qemu"):
        if qemu['status'] == 'running':
            try:
                vm_ip=proxmox.nodes(node['node']).qemu(qemu["vmid"]).agent.get('network-get-interfaces').get('result')
                for x in vm_ip:
                    macadress=x["hardware-address"]
                    if macadress != '00:00:00:00:00:00' and macadress!= 'ee:ee:ee:ee:ee:ee' and x["name"]!='docker0':
                        mactostring=str(macadress)  
                for i in vm_ip:
                    if 'ip-addresses' in i:
                        for j in i['ip-addresses']:
                            if j["prefix"] == 24 and j["ip-address"].startswith("100"):
                                compareid=str(qemu["vmid"])
                                compareip=str(j['ip-address'])
                                if compareid.startswith("100") and compareip.endswith(compareid[3]):
                                    pass
                                    #print("ID:{0} Name: {1}  Mac Adress: {2}  IP Adress: {3} matches" .format(compareid,qemu["name"],mactostring,compareip))
                                elif compareid.startswith("10") and compareip.endswith(compareid[2:]):
                                    pass
                                    #print("ID:{0} Name: {1}  Mac Adress: {2}  IP Adress: {3} matches" .format(compareid,qemu["name"],mactostring,compareip))
                                elif compareid.startswith("1") and compareip.endswith(compareid[1:]):
                                    pass
                                    #print("ID:{0} Name: {1}  Mac Adress: {2} IP Adress: {3} matches" .format(compareid,qemu["name"],mactostring,compareip))
                                else:
                                    print("ID:{0} Name: {1}  Mac Adress: {2}  IP Adress: {3} non matches" .format(compareid,qemu["name"],mactostring,compareip))
                                    count += 1
                                    ip_prefix= '100.101.1.'
                                    eklenecekmac = macadress
                                    eklenecekdescr = qemu["name"]
                                    if compareid.startswith("100"):
                                        eklenecekip = ip_prefix + compareid[3:]
                                        for dhcpd in root.iter('dhcpd'):
                                         for lan in dhcpd.iter('lan'):
                                             for pool in lan.findall('pool'):
                                                    lan.remove(pool)
                                        staticmap=ET.SubElement(lan,'staticmap',attrib={})
                                        staticmap.tail= '\n'
                                        staticmap.text = '\n \t'
                                        mac=ET.SubElement(staticmap,'mac',attrib={})
                                        mac.tail = '\n \t'
                                        mac.text=eklenecekmac
                                        ipaddr=ET.SubElement(staticmap,'ipaddr',attrib={})
                                        ipaddr.tail = '\n \t'
                                        ipaddr.text= eklenecekip
                                        descr=ET.SubElement(staticmap,'descr',attrib={})
                                        descr.tail = '\n \t'
                                        descr.text= eklenecekdescr
                                        winsserver=ET.SubElement(staticmap,'winsserver',attrib={})
                                        winsserver.tail= '\n \t'
                                        dnsserver=ET.SubElement(staticmap,'dnsserver',attrib={})
                                        dnsserver.tail = '\n \t'
                                        ntpserver=ET.SubElement(staticmap,'ntpserver',attrib={})
                                        ntpserver.tail = '\n \t'
                                        pool=ET.SubElement(lan,'pool',attrib={})
                                    elif compareid.startswith("10"):
                                        eklenecekip = ip_prefix + compareid[2:]
                                        for dhcpd in root.iter('dhcpd'):
                                         for lan in dhcpd.iter('lan'):
                                             for pool in lan.findall('pool'):
                                                    lan.remove(pool)
                                        staticmap=ET.SubElement(lan,'staticmap',attrib={})
                                        staticmap.tail= '\n'
                                        staticmap.text = '\n \t'
                                        mac=ET.SubElement(staticmap,'mac',attrib={})
                                        mac.tail = '\n \t'
                                        mac.text=eklenecekmac
                                        ipaddr=ET.SubElement(staticmap,'ipaddr',attrib={})
                                        ipaddr.tail = '\n \t'
                                        ipaddr.text= eklenecekip
                                        descr=ET.SubElement(staticmap,'descr',attrib={})
                                        descr.tail = '\n \t'
                                        descr.text= eklenecekdescr
                                        winsserver=ET.SubElement(staticmap,'winsserver',attrib={})
                                        winsserver.tail= '\n \t'
                                        dnsserver=ET.SubElement(staticmap,'dnsserver',attrib={})
                                        dnsserver.tail = '\n \t'
                                        ntpserver=ET.SubElement(staticmap,'ntpserver',attrib={})
                                        ntpserver.tail = '\n \t'
                                        pool=ET.SubElement(lan,'pool',attrib={})
                                    elif compareid.startswith("1"):
                                        eklenecekip = ip_prefix + compareid[1:]
                                        for dhcpd in root.iter('dhcpd'):
                                         for lan in dhcpd.iter('lan'):
                                             for pool in lan.findall('pool'):
                                                    lan.remove(pool)
                                        staticmap=ET.SubElement(lan,'staticmap',attrib={})
                                        staticmap.tail= '\n'
                                        staticmap.text = '\n \t'
                                        mac=ET.SubElement(staticmap,'mac',attrib={})
                                        mac.tail = '\n \t'
                                        mac.text=eklenecekmac
                                        ipaddr=ET.SubElement(staticmap,'ipaddr',attrib={})
                                        ipaddr.tail = '\n \t'
                                        ipaddr.text= eklenecekip
                                        descr=ET.SubElement(staticmap,'descr',attrib={})
                                        descr.tail = '\n \t'
                                        descr.text= eklenecekdescr
                                        winsserver=ET.SubElement(staticmap,'winsserver',attrib={})
                                        winsserver.tail= '\n \t'
                                        dnsserver=ET.SubElement(staticmap,'dnsserver',attrib={})
                                        dnsserver.tail = '\n \t'
                                        ntpserver=ET.SubElement(staticmap,'ntpserver',attrib={})
                                        ntpserver.tail = '\n \t'
                                        pool=ET.SubElement(lan,'pool',attrib={})
                                vmrestart = proxmox.nodes(node['node']).qemu(qemu["vmid"]).status.post("reboot")
            except (ResourceException,KeyError) as error:
                pass 
tree1 = ET.ElementTree(root)
tree1.write("edited.xml")            
try:
    sftp.put(source_path,destination_path)
    print("Successful file uploading and new file location: {}".format(destination_path))

except IOError:
    print('File uploading errored')
sftp.close()
ssh.close()