kickstart部署及使用

Linux运维:kickstart

: Ago linux运维群:https://hankbook.cn


1.环境检查

[root@m01 ~]# cat /etc/redhat-release 
CentOS release 6.8 (Final)
[root@m01 ~]# uname -r
2.6.32-642.el6.x86_64
[root@m01 ~]# getenforce 
Disabled
[root@m01 ~]# /etc/init.d/iptables stop
[root@m01 ~]# /etc/init.d/iptables status
iptables: Firewall is not running.
[root@m01 ~]# hostname -I
10.0.0.61 172.16.1.61

关闭虚拟机的DHCP服务。一个网段只能出现一个DHCP服务器。不然会出错。

  • 虚拟机网卡采用NAT模式,不要使用桥接模式,因为稍后我们会搭建DHCP服务器,在同一局域网多个DHCP服务会有冲突。
  • VMware的NAT模式的dhcp服务也关闭,避免干扰。

2.安装DHCP

DHCP(Dynamic Host Configuration Protocol,动态主机配置协议)通常被应用在大型的局域网络环境中,主要作用是集中的管理、分配IP地址,使网络环境中的主机动态的获得IP地址、网关地址、DNS服务器地址等信息,并能够提升地址的使用率。
参考链接,DHCP主要6个步骤

安装

[root@m01 ~]# yum -y install dhcp
[root@m01 ~]# rpm -ql dhcp |grep "dhcpd.conf"
/etc/dhcp/dhcpd.conf
/usr/share/doc/dhcp-4.1.1/dhcpd-conf-to-ldap
/usr/share/doc/dhcp-4.1.1/dhcpd.conf.sample
/usr/share/man/man5/dhcpd.conf.5.gz

配置文件

这个文件不改变,新版。旧版需要指定

[root@m01 ~]# cat /etc/sysconfig/dhcpd
# Command line options here
DHCPDARGS=

/etc/dhcp/dhcpd.conf

[root@m01 ~]#  cat /etc/dhcp/dhcpd.conf
#
# DHCP Server Configuration file.
#   see /usr/share/doc/dhcp*/dhcpd.conf.sample
#   see 'man 5 dhcpd.conf'
#

修改配置文件

/etc/dhcp/dhcpd.conf

[root@m01 ~]# vi /etc/dhcp/dhcpd.conf
subnet 172.16.1.0 netmask 255.255.255.0 {
        range 172.16.1.100 172.16.1.200;
        option subnet-mask 255.255.255.0;
        default-lease-time 21600;
        max-lease-time 43200;
        next-server 172.16.1.61;
        filename "/pxelinux.0";
}

启动服务

[root@m01 ~]# /etc/init.d/dhcpd restart
Starting dhcpd:                                            [  OK  ]

查看日志
/var/log/message

Apr 12 10:25:37 Aige dhcpd: Internet Systems Consortium DHCP Server 4.1.1-P1
Apr 12 10:25:37 Aige dhcpd: Copyright 2004-2010 Internet Systems Consortium.
Apr 12 10:25:37 Aige dhcpd: All rights reserved.
Apr 12 10:25:37 Aige dhcpd: For info, please visit https://www.isc.org/software/dhcp/
Apr 12 10:25:37 Aige dhcpd: Not searching LDAP since ldap-server, ldap-port and ldap-base-dn were not specified in the config file
Apr 12 10:25:37 Aige dhcpd: Wrote 0 leases to leases file.
Apr 12 10:25:37 Aige dhcpd: Listening on LPF/eth1/00:0c:29:92:ab:38/172.16.1.0/24
Apr 12 10:25:37 Aige dhcpd: Sending on   LPF/eth1/00:0c:29:92:ab:38/172.16.1.0/24
Apr 12 10:25:37 Aige dhcpd: 
Apr 12 10:25:37 Aige dhcpd: No subnet declaration for eth0 (10.0.0.61).
Apr 12 10:25:37 Aige dhcpd: ** Ignoring requests on eth0.  If this is not what
Apr 12 10:25:37 Aige dhcpd:    you want, please write a subnet declaration
Apr 12 10:25:37 Aige dhcpd:    in your dhcpd.conf file for the network segment
Apr 12 10:25:37 Aige dhcpd:    to which interface eth0 is attached. **
Apr 12 10:25:37 Aige dhcpd: 
Apr 12 10:25:37 Aige dhcpd: Sending on   Socket/fallback/fallback-net

最后查看

[root@m01 ~]# netstat -tunlp|grep dhcp
udp        0      0 0.0.0.0:67    0.0.0.0:*      2083dhcpd 

3.安装tftp

安装

[root@m01 ~]# yum -y install tftp-server

修改配置文件

sed -i '14s#yes#no#' /etc/xinetd.d/tftp

检查69端口

[root@m01 ~]# netstat -tlunp| grep 69
udp  0   0 0.0.0.0:69   0.0.0.0:*   2133/xinetd 

4.安装httpd

安装

[root@m01 ~]# yum install httpd -y

启动

[root@m01 ~]# /etc/init.d/httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 172.16.1.61 for ServerName
                                                           [  OK  ]

虚拟机挂载镜像

[root@m01 ~]# sed -i "277i ServerName 127.0.0.1:80" /etc/httpd/conf/httpd.conf
[root@m01 ~]# /etc/init.d/httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                            [  OK  ]
[root@m01 ~]# mkdir /var/www/html/CentOS-6.8
[root@m01 ~]# mount /dev/cdrom /var/www/html/CentOS-6.8
mount: block device /dev/sr0 is write-protected, mounting read-only
[root@m01 ~]# df
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda3        7116844 1514516   5234152  23% /
tmpfs             246972       0    246972   0% /dev/shm
/dev/sda1         194241   33770    150231  19% /boot
/dev/sr0         3824484 3824484         0 100% /var/www/html/CentOS-6.8

生产环境:把光盘的内容扔进磁盘中。因为光盘的读取非常慢。

5.配置支持PXE的启动程序

PXE引导配置(bootstrap)

syslinux是一个功能强大的引导加载程序,而且兼容各种介质。SYSLINUX是一个小型的Linux操作系统,它的目的是简化首次安装Linux的时间,并建立修护或其它特殊用途的启动盘。如果没有找到pxelinux.0这个文件,可以安装一下。

安装

[root@m01 ~]# yum -y install syslinux

复制启动此单程序文件
tftpboot是tftp的根目录

[root@m01 ~]# cp /usr/share/syslinux/pxelinux.0 /var/lib/tftpboot/

跟启动相关的了一些文件

[root@m01 ~]# cp -a /var/www/html/CentOS-6.8/isolinux/* /var/lib/tftpboot/

pxelinux.cfg是一个目录,它比较怪异

[root@m01 ~]# mkdir -p /var/lib/tftpboot/pxelinux.cfg
[root@m01 ~]# cp /var/www/html/CentOS-6.8/isolinux/isolinux.cfg /var/lib/tftpboot/pxelinux.cfg/default

查看

[root@m01 ~]# ls /var/lib/tftpboot/
boot.cat  grub.conf   isolinux.bin  memtest     pxelinux.cfg  TRANS.TBL     vmlinuz
boot.msg  initrd.img  isolinux.cfg  **pxelinux.0**  splash.jpg    vesamenu.c32

上面就是下图

创建空白虚拟机

配置文件

/var/lib/tftpboot/pxelinux.cfg/default

[root@linux-node1 ~]# vim /var/lib/tftpboot/pxelinux.cfg/default
default vesamenu.c32  # 默认加载一个菜单
#prompt 1             # 开启会显示命令行'boot: '提示符。prompt值为0时则不提示,将会直接启动'default'参数中指定的内容。
timeout 600           # timeout时间是引导时等待用户手动选择的时间,设为1可直接引导,单位为1/10秒。
display boot.msg
# 菜单背景图片、标题、颜色。
menu background splash.jpg
menu title Welcome to CentOS 6.7!
menu color border 0 #ffffffff #00000000
menu color sel 7 #ffffffff #ff000000
menu color title 0 #ffffffff #00000000
menu color tabmsg 0 #ffffffff #00000000
menu color unsel 0 #ffffffff #00000000
menu color hotsel 0 #ff000000 #ffffffff
menu color hotkey 7 #ffffffff #ff000000
menu color scrollbar 0 #ffffffff #00000000
# label指定在boot:提示符下输入的关键字,比如boot:linux[ENTER],这个会启动label linux下标记的kernel和initrd.img文件。
label linux       # 一个标签就是前面图片的一行选项。
  menu label ^Install or upgrade an existing system
  menu default
  kernel vmlinuz  # 指定要启动的内核。同样要注意路径,默认是/tftpboot目录。
  append initrd=initrd.img # 指定追加给内核的参数,initrd.img是一个最小的linux系统
label vesa
  menu label Install system with ^basic video driver
  kernel vmlinuz
  append initrd=initrd.img nomodeset
label rescue
  menu label ^Rescue installed system
  kernel vmlinuz
  append initrd=initrd.img rescue
label local
  menu label Boot from ^local drive
  localboot 0xffff
label memtest86
  menu label ^Memory test
  kernel memtest
  append -

创建ks.cfg文件

通常,我们在安装操作系统的过程中,需要大量的和服务器交互操作,为了减少这个交互过程,kickstart就诞生了。使用这种kickstart,只需事先定义好一个Kickstart自动应答配置文件ks.cfg(通常存放在安装服务器上),并让安装程序知道该配置文件的位置,在安装过程中安装程序就可以自己从该文件中读取安装配置,这样就避免了在安装过程中多次的人机交互,从而实现无人值守的自动化安装。

生成kickstart配置文件的三种方法:

  • 方法1、
    每安装好一台Centos机器,Centos安装程序都会创建一个kickstart配置文件,记录你的真实安装配置。如果你希望实现和某系统类似的安装,可以基于该系统的kickstart配置文件来生成你自己的kickstart配置文件。(生成的文件名字叫anaconda-ks.cfg位于/root/anaconda-ks.cfg)

  • 方法2、Centos提供了一个图形化的kickstart配置工具。在任何一个安装好的Linux系统上运行该工具,就可以很容易地创建你自己的kickstart配置文件。kickstart配置工具命令为redhat-config-kickstart(RHEL3)或system-config-kickstart(RHEL4,RHEL5).网上有很多用CentOS桌面版生成ks文件的文章,如果有现成的系统就没什么可说。但没有现成的,也没有必要去用桌面版,命令行也很简单。

  • 方法3、阅读kickstart配置文件的手册。用任何一个文本编辑器都可以创建你自己的kickstart配置文件。

查看anaconda-ks.cfg

# Kickstart file automatically generated by anaconda.
#version=DEVEL
install
cdrom
lang en_US.UTF-8
keyboard us
network --onboot yes --device eth0 --bootproto static --ip 10.0.0.6 --netmask 255.255.255.0 --gateway 10.0.0.2 --noipv6 --nameserver 10.0.0.2 --hostname centos67
rootpw  --iscrypted $6$2Frfm3Sc/oWdF2Yb$GTS8VbsaeLzAfT46EYJWezKA7VMOnefDAH6anyb12Hu5K1qu1awlpTwBxTjAzXpV/.l983Irdwxo5Rks0QV1p1
firewall --service=ssh
authconfig --enableshadow --passalgo=sha512
selinux --enforcing
timezone --utc Asia/Shanghai
bootloader --location=mbr --driveorder=sda --append="crashkernel=auto rhgb quiet"
# The following is the partition information you requested
# Note that any partitions you deleted are not expressed
# here so unless you clear all partitions first, this is
# not guaranteed to work
#clearpart --none
#part /boot --fstype=ext4 --asprimary --size=200
#part swap --asprimary --size=1024
#part / --fstype=ext4 --grow --asprimary --size=200
repo --name="CentOS"  --baseurl=cdrom:sr0 --cost=100
%packages
@base
@compat-libraries
@core
@debugging
@development
@server-policy
@workstation-policy
python-dmidecode
sgpio
device-mapper-persistent-data
systemtap-client

ks.cfg详解

官网文档

CentOS6 : https://access.redhat.com/knowledge/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Installation_Guide/s1-kickstart2-options.html

官网自带中文版,选一下语言即可
ks.cfg文件组成大致分为3段

  • 命令段
    键盘类型,语言,安装方式等系统的配置,有必选项和可选项,如果缺少某项必选项,安装时会中断并提示用户选择此项的选项

  • 软件包段

%packages
@groupname:指定安装的包组
package_name:指定安装的包
-package_name:指定不安装的包

在安装过程中默认安装的软件包,安装软件时会自动分析依赖关系。

  • 脚本段(可选)
%pre:安装系统前执行的命令或脚本(由于只依赖于启动镜像,支持的命令很少)
%post:安装系统后执行的命令或脚本(基本支持所有命令)

关键字	       含义
install	     告知安装程序,这是一次全新安装,而不是升级upgrade。
url          --url=" "	通过FTP或HTTP从远程服务器上的安装树中安装。
url          --url="http://10.0.0.7/CentOS-6.8/"
url          --url ftp://<username>:<password>@<server>/<dir>
nfs	         从指定的NFS服务器安装。
nfs          --server=nfsserver.example.com --dir=/tmp/install-tree
text	     使用文本模式安装。
lang	     设置在安装过程中使用的语言以及系统的缺省语言。lang en_US.UTF-8
keyboard  	 设置系统键盘类型。keyboard us
zerombr	     清除mbr引导信息。
bootloader	 系统引导相关配置。
bootloader   --location=mbr --driveorder=sda --append="crashkernel=auto rhgb quiet"
--location=,指定引导记录被写入的位置.有效的值如下:mbr(缺省),partition(在包含内核的分区的第一个扇区安装引导装载程序)或none(不安装引导装载程序)。
--driveorder,指定在BIOS引导顺序中居首的驱动器。
--append=,指定内核参数.要指定多个参数,使用空格分隔它们。

network	      为通过网络的kickstart安装以及所安装的系统配置联网信息。
network --bootproto=dhcp --device=eth0 --onboot=yes --noipv6 --hostname=CentOS6
--bootproto=[dhcp/bootp/static]中的一种,缺省值是dhcp。bootp和dhcp被认为是相同的。
static方法要求在kickstart文件里输入所有的网络信息。
network --bootproto=static --ip=10.0.0.100 --netmask=255.255.255.0 --gateway=10.0.0.2 --nameserver=10.0.0.2
请注意所有配置信息都必须在一行上指定,不能使用反斜线来换行。
--ip=,要安装的机器的IP地址.
--gateway=,IP地址格式的默认网关.
--netmask=,安装的系统的子网掩码.
--hostname=,安装的系统的主机名.
--onboot=,是否在引导时启用该设备.
--noipv6=,禁用此设备的IPv6.
--nameserver=,配置dns解析.
timezone	   设置系统时区。timezone --utc Asia/Shanghai
authconfig	   系统认证信息。authconfig --enableshadow --passalgo=sha512
设置密码加密方式为sha512 启用shadow文件。
rootpw	       root密码
clearpart	   清空分区。clearpart --all --initlabel
--all          从系统中清除所有分区,--initlable 初始化磁盘标签
part	       磁盘分区。
part /boot --fstype=ext4 --asprimary --size=200
part swap --size=1024
part / --fstype=ext4 --grow --asprimary --size=200
--fstype=,为分区设置文件系统类型.有效的类型为ext2,ext3,swap和vfat。
--asprimary,强迫把分区分配为主分区,否则提示分区失败。
--size=,以MB为单位的分区最小值.在此处指定一个整数值,如500.不要在数字后面加MB。
--grow,告诉分区使用所有可用空间(若有),或使用设置的最大值。
firstboot	    负责协助配置redhat一些重要的信息。
firstboot --disable
selinux	        关闭selinux。selinux --disabled
firewall	    关闭防火墙。firewall --disabled
logging	        设置日志级别。logging --level=info
reboot	        设定安装完成后重启,此选项必须存在,不然kickstart显示一条消息,并等待用户按任意键后才重新引导,也可以选择halt关机。

安装配置文件

/var/www/html/ks_config

[root@m01 ks_config]# pwd
/var/www/html/ks_config
[root@m01 ks_config]# ll
total 28
-rw-r--r-- 1 root root  970 Nov  8 15:27 CentOS-6.8-ks.cfg
-rw-r--r-- 1 root root 2572 May 27  2016 CentOS-Base.repo
-rw-r--r-- 1 root root 1083 May 27  2016 epel.repo
-rw-r--r-- 1 root root  354 Nov  8 15:31 hosts
-rw-r--r-- 1 root root 3480 Mar 19 15:56 optimization.sh
-rw-r--r-- 1 root root 3966 May 27  2016 sshd_config
-rw-r--r-- 1 root root 1602 May 27  2016 sysctl.conf

[root@m01 ks_config]# cat CentOS-6.8-ks.cfg

# Kickstart Configurator for CentOS 6.7 by yao zhang
install
url --url="http://172.16.1.61/CentOS-6.8/"
text
lang en_US.UTF-8
keyboard us
zerombr
bootloader --location=mbr --driveorder=sda --append="crashkernel=auto rhgb quiet"
network --bootproto=dhcp --device=eth1 --onboot=yes --noipv6 --hostname=CentOS6
timezone --utc Asia/Shanghai
authconfig --enableshadow --passalgo=sha512
rootpw  --iscrypted $6$X20eRtuZhkHznTb4$dK0BJByOSAWSDD8jccLVFz0CscijS9ldMWwpoCw/ZEjYw2BTQYGWlgKsn945fFTjRC658UXjuocwJbAjVI5D6/
clearpart --all --initlabel
part /boot --fstype=ext4 --asprimary --size=200
part swap --size=1024
part / --fstype=ext4 --grow --asprimary --size=200
firstboot --disable
selinux --disabled
firewall --disabled
logging --level=info
reboot

%packages
@base
@compat-libraries
@debugging
@development
tree
nmap
sysstat
lrzsz
dos2unix
telnet

%post
wget -O /tmp/optimization.sh http://172.16.1.61/ks_config/optimization.sh &>/dev/null
/bin/sh /tmp/optimization.sh
%end

[root@m01 ks_config]# cat CentOS-Base.repo

# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client.  You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the 
# remarked out baseurl= line instead.
#
#
 
[base]
name=CentOS-$releasever - Base - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/os/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/os/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-6
 
#released updates 
[updates]
name=CentOS-$releasever - Updates - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/updates/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/updates/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-6
 
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/extras/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/extras/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-6
 
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/centosplus/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/centosplus/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
gpgcheck=1
enabled=0
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-6
 
#contrib - packages by Centos Users
[contrib]
name=CentOS-$releasever - Contrib - mirrors.aliyun.com
failovermethod=priority
baseurl=http://mirrors.aliyun.com/centos/$releasever/contrib/$basearch/
        http://mirrors.aliyuncs.com/centos/$releasever/contrib/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=contrib
gpgcheck=1
enabled=0
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-6

[root@m01 ks_config]# cat epel.repo

[epel]
name=Extra Packages for Enterprise Linux 6 - $basearch
baseurl=http://mirrors.aliyun.com/epel/6/$basearch
        http://mirrors.aliyuncs.com/epel/6/$basearch
#mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
 
[epel-debuginfo]
name=Extra Packages for Enterprise Linux 6 - $basearch - Debug
baseurl=http://mirrors.aliyun.com/epel/6/$basearch/debug
        http://mirrors.aliyuncs.com/epel/6/$basearch/debug
#mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-6&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
gpgcheck=0
 
[epel-source]
name=Extra Packages for Enterprise Linux 6 - $basearch - Source
baseurl=http://mirrors.aliyun.com/epel/6/SRPMS
        http://mirrors.aliyuncs.com/epel/6/SRPMS
#mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-source-6&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
gpgcheck=0

[root@m01 ks_config]# cat hosts

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
172.16.1.5      lb01
172.16.1.6      lb02
172.16.1.7      web02
172.16.1.8      web01
172.16.1.51     db01 db01.etiantian.org
172.16.1.31     nfs01
172.16.1.41     backup
172.16.1.61     m01
####

[root@m01 ks_config]# cat optimization.sh
脚本需要注意的是,EOF是用linux内的TAB键

#!/bin/bash
. /etc/init.d/functions

Ip=172.16.1.61
Port=80
ConfigDir=ks_config

# Judge Http server is ok?
PortNum=`nmap $Ip  -p $Port 2>/dev/null|grep open|wc -l`
[ $PortNum -lt 1 ] && {
echo "Http server is bad!"
exit 1
}

# Defined result function
function Msg(){
        if [ $? -eq 0 ];then
          action "$1" /bin/true
        else
          action "$1" /bin/false
        fi
}

# Defined IP function
function ConfigIP(){
	Suffix=`ifconfig eth1|awk -F "[ .]+" 'NR==2 {print $6}'`
	cat >/etc/sysconfig/network-scripts/ifcfg-eth0 <<-END
	DEVICE=eth0
	TYPE=Ethernet
	ONBOOT=yes
	NM_CONTROLLED=yes
	BOOTPROTO=none
	IPADDR=10.0.0.$Suffix
	PREFIX=24
	GATEWAY=10.0.0.2
	DNS1=10.0.0.2
	DEFROUTE=yes
	IPV4_FAILURE_FATAL=yes
	IPV6INIT=no
	NAME="System eth0"
	END
	Msg "config eth0"
        cat >/etc/sysconfig/network-scripts/ifcfg-eth1 <<-END
	DEVICE=eth1
	TYPE=Ethernet
	ONBOOT=yes
	NM_CONTROLLED=yes
	BOOTPROTO=none
	IPADDR=172.16.1.$Suffix
	PREFIX=24
	DEFROUTE=yes
	IPV4_FAILURE_FATAL=yes
	IPV6INIT=no
	NAME="System eth1"
	END
        Msg "config eth1"
}

# Defined Yum source Functions
function yum(){
	YumDir=/etc/yum.repos.d
	[ -f "$YumDir/CentOS-Base.repo" ] && cp $YumDir/CentOS-Base.repo{,.ori} 
	wget -O $YumDir/CentOS-Base.repo http://$Ip:$Port/$ConfigDir/CentOS-Base.repo &>/dev/null &&\
	wget -O $YumDir/epel.repo http://$Ip:$Port/$ConfigDir/epel.repo &>/dev/null &&\
	Msg "YUM source"
}


# Defined add Ordinary users Functions
function AddUser(){
	useradd oldboy &>/dev/null &&\
	echo "123456"|passwd --stdin oldboy &>/dev/null &&\
	sed  -i '98a oldboy    ALL=(ALL)       NOPASSWD:ALL'  /etc/sudoers &&\
	visudo -c &>/dev/null
	Msg "AddUser oldboy"
}

# Defined Hide the system version number Functions
function HideVersion(){
	[ -f "/etc/issue" ] && >/etc/issue
        Msg "Hide issue"
	[ -f "/etc/issue.net" ] && > /etc/issue.net
        Msg "Hide issue.net"
}


# Defined SSHD config Functions
function sshd(){
	SshdDir=/etc/ssh
	[ -f "$SshdDir/sshd_config" ] && /bin/mv $SshdDir/sshd_config{,.ori}
	wget -O $SshdDir/sshd_config http://$Ip:$Port/$ConfigDir/sshd_config &>/dev/null &&\
	chmod 600 $SshdDir/sshd_config
        Msg "sshd config"
}

# Defined OPEN FILES Functions
function openfiles(){
	[ -f "/etc/security/limits.conf" ] && {
	echo '*  -  nofile  65535' >> /etc/security/limits.conf
        Msg "open files"
	}
}

# Defined Kernel parameters Functions
function kernel(){
        KernelDir=/etc
        [ -f "$KernelDir/sysctl.conf" ] && /bin/mv $KernelDir/sysctl.conf{,.ori}
	wget -O $KernelDir/sysctl.conf http://$Ip:$Port/$ConfigDir/sysctl.conf &>/dev/null
        Msg "Kernel config"
}

# Defined hosts file Functions
function hosts(){
        HostsDir=/etc
        [ -f "$HostsDir/hosts" ] && /bin/mv $HostsDir/hosts{,.ori}
        wget -O $HostsDir/hosts http://$Ip:$Port/$ConfigDir/hosts &>/dev/null
        Msg "Hosts config"
}

# Defined System Startup Services Functions
function boot(){
	for oldboy in `chkconfig --list|grep "3:on"|awk '{print $1}'|grep -vE "crond|network|rsyslog|sshd"`
	  do 
	   chkconfig $oldboy off
	done
	Msg "BOOT config"
}

# Defined Time Synchronization Functions
function Time(){
	echo "#time sync by zhangyao at $(date +%F)" >>/var/spool/cron/root
	echo '*/5 * * * * /usr/sbin/ntpdate ntp1.aliyun.com &>/dev/null' >>/var/spool/cron/root
        Msg "Time Synchronization"
}

# Defined main Functions
function main(){
	ConfigIP
	yum
	AddUser
	HideVersion
	sshd
	openfiles
	kernel
	hosts
	boot
	Time		
}

main

[root@m01 ks_config]# cat sshd_config

#	$OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options change a
# default value.
Port 52113
PermitRootLogin no
PermitEmptyPasswords no
UseDNS no
GSSAPIAuthentication no
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

# Disable legacy (protocol version 1) support in the server for new
# installations. In future the default will change to require explicit
# activation of protocol 1
Protocol 2

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile	.ssh/authorized_keys
#AuthorizedKeysCommand none
#AuthorizedKeysCommandRunAs nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication yes

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
#GSSAPIAuthentication no
GSSAPIAuthentication yes
#GSSAPICleanupCredentials yes
GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing, 
# and session processing. If this is enabled, PAM authentication will 
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no
UsePAM yes

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem	sftp	/usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#	X11Forwarding no
#	AllowTcpForwarding no
#	ForceCommand cvs server

[root@m01 ks_config]# cat sysctl.conf

# Kernel sysctl configuration file for Red Hat Linux
#
# For binary values, 0 is disabled, 1 is enabled.  See sysctl(8) and
# sysctl.conf(5) for more details.

# Controls IP packet forwarding
net.ipv4.ip_forward = 0

# Controls source route verification
net.ipv4.conf.default.rp_filter = 1

# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0

# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0

# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1

# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1

# Disable netfilter on bridges.
net.bridge.bridge-nf-call-ip6tables = 0
net.bridge.bridge-nf-call-iptables = 0
net.bridge.bridge-nf-call-arptables = 0

# Controls the default maxmimum size of a mesage queue
kernel.msgmnb = 65536

# Controls the maximum size of a message, in bytes
kernel.msgmax = 65536

# Controls the maximum shared segment size, in bytes
kernel.shmmax = 68719476736

# Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296
net.ipv4.tcp_fin_timeout = 2
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.ip_local_port_range = 4000    65000
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.route.gc_timeout = 100
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.core.somaxconn = 16384
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_max_orphans = 16384

整合编辑default配置文件

 >/var/lib/tftpboot/pxelinux.cfg/default
cat>/var/lib/tftpboot/pxelinux.cfg/default<<EOF
default ks
prompt 0
label ks
  kernel vmlinuz
  append initrd=initrd.img ks=http://172.16.1.61/ks_config/CentOS-6.8-ks.cfg ksdevice=eth1
EOF
# 最精简配置
[root@linux-node1 ~]# vim /var/lib/tftpboot/pxelinux.cfg/default
default ks
prompt 0
label ks
  kernel vmlinuz
  append initrd=initrd.img ks=http://172.16.1.61/ks_config/CentOS-6.8-ks.cfg # 告诉安装程序ks.cfg文件在哪里
# append initrd=initrd.img ks=http://172.16.1.61/ks_config/CentOS-6.8-ks.cfg ksdevice=eth1
# ksdevice=eth1代表当客户端有多块网卡的时候,要实现自动化需要设置从eth1安装,不指定的话,安装的时候系统会让你选择,那就不叫全自动化了。

知识扩展

由于多个客户端可以从一个PXE服务器引导,PXE引导映像使用了一个复杂的配置文件搜索方式来查找针对客户机的配置文件。如果客户机的网卡的MAC地址为8F:3H:AA:6B:CC:5D,对应的IP地址为10.0.0.195,那么客户机首先尝试以MAC地址为文件名匹配的配置文件,如果不存在就以IP地址来查找。根据上述环境针对这台主机要查找的以一个配置文件就是 /tftpboot/pxelinux.cfg/01-8F:3H:AA:6B:CC:5D。如果该文件不存在,就会根据IP地址来查找配置文件了,这个算法更复杂些,PXE映像查找会根据IP地址16进制命名的客户机配置文件。例如:10.0.0.195对应的16进制的形式为C0A801C3。(可以通过syslinux软件包提供的gethostip命令将10进制的IP转换为16进制)

如果C0A801C3文件不存在,就尝试查找C0A801C文件,如果C0A801C也不存在,那么就尝试C0A801文件,依次类推,直到查找C文件,如果C也不存在的话,那么最后尝试default文件。

总体来说,pxelinux搜索的文件的顺序是:

/tftpboot/pxelinux.cfg/01-88-99-aa-bb-cc-dd
/tftpboot/pxelinux.cfg/C0A801C3
/tftpboot/pxelinux.cfg/C0A801C
/tftpboot/pxelinux.cfg/C0A801
/tftpboot/pxelinux.cfg/C0A80
/tftpboot/pxelinux.cfg/C0A8
/tftpboot/pxelinux.cfg/C0A
/tftpboot/pxelinux.cfg/C0
/tftpboot/pxelinux.cfg/C
/tftpboot/pxelinux.cfg/default

应用:如果已经从厂商获取了服务器MAC地址,就可以差异化定制安装服务器了。

posted @ 2017-04-12 16:07  汉克书  阅读(6054)  评论(0编辑  收藏  举报