代码改变世界

PythonScript_demo--搭建PXE服务器

2016-02-29 02:34  云物互联  阅读(168)  评论(0编辑  收藏  举报

前言

是一个测试向的Demo,在实验环境中改改还是可以用的,有助理解PXE服务器的原理。可以结合PXE服务器原理细节来看,传送门:点这里

软件环境

  • 系统
    • RHEL7
  • 软件
    • Python 27
    • RHEL7 ISO文件

Code

PXE Server所需要的所有服务的配置文件都是以重定向输出的方式来写入。建议在干净的系统中测试。 : )

#!/usr/local/bin/python
#coding=utf8
import commands
import os

def set_network(ipaddr,gateway,dns):
    "网络设置!"
    IPADDR = ipaddr
    GATEWAY = gateway
    DNS = dns
    if len(IPADDR) != 0 and len(GATEWAY) != 0 and len(DNS) != 0:
        checkIP1=commands.getstatusoutput('nmcli connection modify eno16777736 ipv4.addresses "%s %s" ipv4.dns "%s" ipv4.method manual connection.autoconnect yes' % (IPADDR,GATEWAY,DNS))
        checkIP2=commands.getstatusoutput('nmcli connection down eno16777736')
        checkIP3=commands.getstatusoutput('nmcli connection up eno16777736')
        if checkIP1[0] == 0 and checkIP2[0] == 0 and checkIP3[0]== 0:
            print '成功设定IP为%s:' % IPADDR
            print '正在关闭防火墙...'
            return 0
        else:return 1
def set_firewall():
    "防火墙设置!"
    commands.getstatusoutput('systemctl mask ebtables.service')
    commands.getstatusoutput('systemctl mask iptables.service')
    commands.getstatusoutput('systemctl stop firewalld.service')
    return 0
def set_yum(yumDir):
    "yum源配置!"
    MKDIR = yumDir
    checkMkdir=commands.getstatusoutput('mkdir -p %s' % MKDIR)
    checkMount=commands.getstatusoutput('mount /dev/cdrom %s' % MKDIR)
    if checkMkdir[0] == 0 and checkMount[0] == 0:
    checkYum1 = commands.getstatusoutput('printf \'[local-video]\nname=local-video\nbaseurl=file://%s\nenabled=1\ngpgcheck=0\n\' > /etc/yum.repos.d/local.repo' % MKDIR)
    checkYum2 = commands.getstatusoutput('yum list')
    if checkYum1[0] == 0 and checkYum2[0] ==0:
        return 0

def set_dhcp(subNet,subMask,subAddrMix,subAddrMax,gateway,ipaddr):
    SUBMASK = subMask
    SUBADDRMIX = subAddrMix
    SUBADDRMAX = subAddrMax
    SUBROUTERS = subRouters
    GATEWAY = gateway
    IPADDR = ipaddr
    inDhcp=commands.getstatusoutput('yum install -y dhcp')
    if inDhcp[0] == 0:print '安装DHCP成功!'
    checkDhcp=commands.getstatusoutput('printf \'default-lease-time 600;\nmax-lease-time 7200;\nlog-facility local7;\nsubnet %s netmask %s {\n range %s %s;\n option routers %s;\n option broadcast-address 192.168.8.255;\n default-lease-time 601;\n max-lease-time 7201;\n next-server %s;\n filename "/pxelinux.0";\n}\n\' > /etc/dhcp/dhcpd.conf' % (SUBNET,SUBMASK,SUBADDRMIX,SUBADDRMAX,GATEWAY,IPADDR)) 
    commands.getstatusoutput('systemctl restart dhcpd.service')
    commands.getstatusoutput('systemctl enable dhcpd.service')
    checkDhcp=commands.getstatusoutput('netstat -lpunt | grep :67')
    if checkDhcp[0] == 0:return 0
    else:return 1

def set_tftp():
    "配置tftp"
    inTftp=commands.getstatusoutput('yum install -y tftp-server')
    if inTftp[0] == 0:print 'tftp install Successful!'
    inSyslinux=commands.getstatusoutput('yum install -y syslinux')
    if inSyslinux[0] == 0:print 'syslinux install Successful!'
    os.system('cp /usr/share/syslinux/pxelinux.0 /var/lib/tftpboot')
    os.system('cp %s/isolinux/vmlinuz %s/isolinux/initrd.img %s/isolinux/boot.msg /var/lib/tftpboot' % (MKDIR,MKDIR,MKDIR))
    os.system('mkdir /var/lib/tftpboot/pxelinux.cfg')
    checkTftp=commands.getstatusoutput('printf "default linux\ntimeout 600\ndisplay boot.msg\nmenu clear\nmenu background splash.png\nmenu title Red Hat Enterprise Linux 7.0\nmenu vshift 8\nmenu rows 18\nmenu margin 8\nmenu helpmsgrow 15\nmenu tabmsgrow 13\nmenu color border *\nmenu color sel 0\nmenu color title 0\nmenu color tabmsg 0\nmenu color unsel 0\nmenu color hotsel 0\nmenu color hotkey 0\nmenu color help 0\nmenu color scrollbar 0\nmenu color timeout 0\nmenu color timeout_msg 0\nmenu color cmdmark 0\nmenu color cmdline 0\nmenu tabmsg Press Tab for full configuration options on menu items.\nmenu separator\nmenu separator\nlabel linux\n  menu label ^Install Red Hat Enterprise Linux 7.0\n  kernel vmlinuz\n  append initrd=initrd.img inst.stage2=http://%s/cdrom ks=http://%s/jmilk.cfg quiet\nlabel check\n  menu label Test this ^media & install Red Hat Enterprise Linux 7.0\n  menu default\n  kernel vmlinuz\n  append initrd=initrd.img inst.stage2=hd:LABEL=RHEL-7.0\x20Server.x86_64 rd.live.check quiet\nmenu separator\nmenu begin ^Troubleshooting\n  menu title Troubleshooting\nlabel vesa\n  menu indent count 5\n  menu label Install Red Hat Enterprise Linux 7.0 in ^basic graphics mode\n  text help\n  Try this option out if you\'re having trouble installing\n       Red Hat Enterprise Linux 7.0.\n  endtext\n  kernel vmlinuz\n  append initrd=initrd.img inst.stage2=hd:LABEL=RHEL-7.0\x20Server.x86_64 xdriver=vesa nomodeset quiet\nlabel rescue\n  menu indent count 5\n  menu label ^Rescue a Red Hat Enterprise Linux system\n  text help\n  If the system will not boot, this lets you access files\n       and edit config files to try to get it booting again.\n  endtext\n  kernel vmlinuz\n  append initrd=initrd.img inst.stage2=hd:LABEL=RHEL-7.0\x20Server.x86_64 rescue quiet\nlabel memtest\n  menu label Run a ^memory test\n  text help\n       If your system is having issues, a problem with your\n  system\'s memory may be the cause. Use this utility to\n see if the memory is working correctly.\n  endtext\n  kernel memtest\nmenu separator\nlabel local\n  menu label Boot from ^local drive\n  localboot 0xffff\nmenu separator\nmenu separator\nlabel returntomain\n  menu label Return to ^main menu\n  menu exit\nmenu end\n" > /var/lib/tftpboot/pxelinux.cfg/default' % (GATEWAY,GATEWAY))
    checkTftp=commands.getstatusoutput('printf "service tftp\n{\n       socket_type             = dgram\n       protocol                = udp\n wait                    = yes\n user                    = root\n        server                  = /usr/sbin/in.tftpd\n  server_args             = -s /var/lib/tftpboot\n        disable                 = no\n  per_source              = 11\n  cps                     = 100 2\n       flags                   = IPv4\n}\n" > /etc/xinetd.d/tftp')
    os.system('systemctl restart xinetd.service')
    checkTftpPort=commands.getstatusoutput('netstat -lputn | grep :69')
    if checkTftpPort[0] == 0:return 0
    else:return 1

def set_http():
    os.system('mkdir /var/www/html/cdrom')
    checkMountHtml=commands.getstatusoutput('mount /dev/cdrom /var/www/html/cdrom')
    commands.getstatusoutput('systemctl restart httpd.service')
    commands.getstatusoutput('systemctl enable httpd.service')
    checkHttp=commands.getstatusoutput('netstat -lputn | grep :80')
    if checkHttp[0] == 0:
        return 0
    else:
        return 1

def set_kickstart():
    kickString='install\nkeyboard \'us\'lnreboot\nrootpw --iscrypted $1$xzjcWSZ/$TKDTy17oHtL9o2PW2X13c/\ntimezone Asia/Shanghai\nurl --url="http://'+GATEWAY+'/cdrom"\nlang zh_CN\nfirewall --disabled\nnetwork  --bootproto=dhcp --device=eth0\nauth  --useshadow  --passalgo=sha512\ngraphical\nfirstboot --disable\nselinux --disabled\nbootloader --location=mbr\nzerombr\nclearpart --all --initlabel\npart /boot --fstype="xfs" --size=200\npart / --fstype="xfs" --size=51200\npart /var --fstype="xfs" --size=10240\npart swap --fstype="swap" --size=4096\npart /tmp --fstype="xfs" --size=10240\n%post\nuseradd -u 9999 jmilk\n%end\n%packages\n@backup-server\n@base\n@compat-libraries\n@core\n@desktop-debugging\n@development\n@dial-up\n@directory-server\n@dns-server\n@file-server\n@fonts\n@ftp-server\n@gnome-desktop\n@guest-agents\n@guest-desktop-agents\n@hardware-monitoring\n@identity-management-server\n@infiniband\n@input-methods\n@internet-browser\n@java-platform\n@kde-desktop\n@large-systems\n@load-balancer\n@mail-server\n@mainframe-access\n@mariadb\n@multimedia\n@network-file-system-client\n@performance\n@postgresql\n@print-client\n@print-server\n@remote-desktop-clients\n@remote-system-management\n@smart-card\n@virtualization-client\n@virtualization-hypervisor\n@virtualization-tools\n@x11\n%end\n'
    os.system('touch /var/www/html/jmilk.cfg')
    kickFile=open('/var/www/html/jmilk.cfg','w+')
    kickFile.writelines(kickString)
    kickFile.flush()
    return 0
if __name__ == '__main__':
    "开始搭建PXE Server"

    print '网络设置...'
    while True:
        ipaddr=raw_input('\033[36;1m请输入你要设定的IP/MASK:\033[0m')     #为Output配色
        gateway=raw_input('\033[36;1m请输入你要设定的网关:\033[0m')
        dns=raw_input('\033[36;1m请输入你要设定的DNS:\033[0m')
        if len(IPADDR) != 0 and len(GATEWAY) != 0 and len(DNS) != 0:
            check_network = set_network(ipaddr,gateway,dns)
            if check_network == 0:break
        else:
            print '\033[31;1m请重新输入正确网络配置...\033[0m'

    print '关闭防火墙...'
    while True:
        check_firewall = set_firewall()
        if check_firewall == 0:
            print '防火墙关闭OK!'
            break
        else:
            print '防火墙关闭失败...尝试重新关闭...'

    print '配置yum源...'
    while True:
        yumDir=raw_input('请输入你要挂载光盘的目录(绝对路径):')
        lengthDir=len(yumDir)
        if lengthDir != 0:
            check_yum = set_yum(yumDir)
                if check_yum == 0:
                    print 'yum源配置成功!'
                    break
                else:
                    print 'yum源配置失败,重新输入目录!'
        else:
            print '挂载目录不能为空,重新输入目录!'

    print '搭建DHCP...'
    while True:
        ipaddr=raw_input('请输入你的IP地址:')
        subNet=raw_input('请输入要配置的DHCP子网(subnet):')
        subMask=raw_input('请输入要配置的DHCP子网掩码:')
        subAddrMix=raw_input('请输入地址池的最小ip:')
        subAddrMax=raw_input('请输入地址池的最大ip:')
        subRouters=raw_input('请输入网关IP:')
        if subNet != '' and subMask != '' and subAddrMix != '' and subAddrMax != '' and subRuters != '':
        check_dhcp = set_dhcp(subNet,subMask,subAddrMix,subAddrMax,gateway,ipaddr)
        if check_dhcp == 0:
            print 'DHCP running!'
            break
        else:
            print 'DHCP 启动失败,请重新输入...'

    print '搭建tftp...'
    while True:
        check_tftp = set_tftp()
        if check_tftp == 0:
            print 'tftp running!'
            break
        else:
            print 'tftp 启动失败...尝试重新启动...'

    print '搭建http...'
    while True:
        check_http = set_http()
        if check_http == 0:
            print 'httpd running!'
            break
        else:
            print 'httpd 启动失败...尝试重新启动...'

    print '正在生成无人值守文件...'
        check_kickstart = set_kickstart()
        if check_kickstart == 0:
            print 'PXE配置完毕!请打开虚拟机测试...'