7-29 9 views
背景
考虑要通过mac指定安装不同的操作系统,首先这些信息都已经录入到了CMDB中,通过API可以获取到,如下样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
[{ 'number': '192.168.1.103', 'ip': '192.168.1.103', 'raid': None, 'get_os': 'RedHat 6.8', 'get_pxe': 'PXE', 'get_rsync_flg': 'False', 'get_raid': None, 'get_ip': None, 'get_mac': '22:44:FF:77:44:78' }, { 'number': '192.168.1.132', 'ip': '192.168.1.132', 'raid': None, 'get_os': 'CentOS 7.3', 'get_pxe': 'PXE', 'get_rsync_flg': 'False', 'get_raid': None, 'get_ip': None, 'get_mac': '22:00:FF:EE:44:74' }] |
准备工作
dhcp模板
个人习惯,我在脚本的所在目录下,创建了一个子目录“templates”,并将我的dhcp模板文件放在这个目录名,并取名叫”dhcpd.conf.j2″
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
[root@localhost ~]# vim templates/dhcpd.conf.j2 default-lease-time 600; max-lease-time 7200; log-facility local7; subnet {{ network.get('subnet')[0] }} netmask {{ network.get('subnet')[1] }} { range {{ network.get('subnet_range')[0] }} {{ network.get('subnet_range')[1] }}; option routers {{ network.get('gateway') }}; } {% for hostname,server_info in pxe_server.items() %} host {{ hostname }} { hardware ethernet {{server_info["mac"] }}; next-server {{ network.get('gateway') }}; fixed-address {{ server_info["ip"] }}; filename "{{ server_info["pxe_os"] }}/pxelinux.0"; } {% endfor %} |
渲染脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
[root@localhost ~]# vim dhcp_flush.py #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Eric Winn # @Email : eng.eric.winn@gmail.com # @Time : 2018-05-18 13:46 # @Version : 1.0 # @File : dhcp_flush # @Software : PyCharm import sys import json import datetime # DHCP network = { 'subnet': [ '192.168.1.0', '255.255.255.0' ], 'subnet_range': [ '192.168.1.100', '192.168.1.200' ], 'gateway': '192.168.1.1', 'nextserver': '192.168.1.55' #pxe server } token = 'aaaaaae1909768eebbbbbbd51886eeeeeeeeeeee' host = '10.9.54.4' headers = {'Authorization': 'token ' + token} url = "http://{host}/api/assets/v1/pxe-assets/".format(host=host) #模板文件所在目录 templateDir = './templates' template_list = { 'dhcp': [ 'dhcpd.conf.j2', #dhcp模板文件 '/etc/dhcp/', # dhcp配置文件目录 ], } class render_file(): def __init__(self, templateDir, templates): try: from jinja2 import FileSystemLoader, Environment except ImportError as e: print('%s\nPlease use `pip install -r requirements.txt` to install.' % e) sys.exit(0) TemplateLoader = FileSystemLoader(searchpath=templateDir) TemplateEnv = Environment(loader=TemplateLoader) self.template = TemplateEnv.get_template(templates[0]) self.exportFileName = templates[0] + datetime.datetime.now().strftime('%Y-%m-%-d-%H-%M-%S') self.service_config_file_name = templates[1] self.result = None def make(self, get_pxe_server_list, network=None): # 渲染 self.result = self.template.render(pxe_server=get_pxe_server_list, network=network) def export(self, filename, key=None): with open(self.exportFileName, 'w') as f: f.write(self.result) import shutil from subprocess import call # 将渲染后的dhcp配置文件copy到dhcp配置文件目录下,覆盖已有的配置文件 shutil.copy(self.exportFileName, self.service_config_file_name + filename) # dhcp配置文件渲染后,重启dhcp服务 if key == 'dhcp': sys_ret = call("systemctl restart dhcpd", shell=True) if sys_ret: SystemError({'msg': 'dhcpd start is failed'}) def get_pxe_server_list(): try: import requests except ImportError as e: print('%s\nPlease use `pip install -r requirements.txt` to install.' % e) sys.exit(0) # 调用api req = requests.get(url, headers=headers) req = json.loads(req.text) pxe_server = dict() # 获取需要的字段,用于渲染 for item in req: sie = {} sie['ip'] = item['ip'] sie['mac'] = item.get('get_mac', None) if not item['get_os']: continue sie['pxe_os'] = str(item['get_os']).replace(' ', '.') pxe_server[item['number']] = sie return pxe_server if __name__ == '__main__': pxe_server_list = get_pxe_server_list() print(pxe_server_list) if not len(pxe_server_list): print('没有获取到要安装系统的主机') SystemExit(1) # dhcp render = render_file(templateDir, template_list.get('dhcp')) render.make(pxe_server_list, network) render.export('dhcpd.conf', 'dhcp') |
渲染后的结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
[root@localhost ~]# cat /etc/dhcp/dhcpd.conf default-lease-time 600; max-lease-time 7200; log-facility local7; subnet 192.168.1.0 netmask 255.255.255.0 { range 192.168.1.100 192.168.1.200; option routers 192.168.1.1; } host 192.168.1.103 { hardware ethernet 22:44:FF:77:44:78; next-server 192.168.1.1; fixed-address 192.168.1.55; filename "RedHat.6.8/pxelinux.0"; } host 192.168.1.132 { hardware ethernet 22:00:FF:EE:44:74; next-server 192.168.1.1; fixed-address 192.168.1.55; filename "CentOS.7.3/pxelinux.0"; } |
如果想赏钱,可以用微信扫描下面的二维码,一来能刺激我写博客的欲望,二来好维护云主机的费用; 另外再次标注博客原地址 itnotebooks.com 感谢!
