Red Hat Training

A Red Hat training course is available for Red Hat Enterprise Linux

27.3.5. 安装后脚本

您可以添加系统在安装结束后但在第一次重启该系统之前要运行的命令,。这个部分必须放在 Kickstart 文件末尾,在 第 27.3.1 节 “Kickstart 命令和选项” 中描述的 Kickstart 命令后面,且必须以 %post 开头并以 % end 结尾。如果您的 Kickstart 文件还包括 %pre 部分,%pre 和 %post 部分的顺序无关紧要。
本节对安装其他软件或配置其他名称服务器等功能很有用。安装后脚本在 chroot 环境中运行,因此从安装介质复制脚本或 RPM 软件包等任务在默认情况下不起作用。您可以使用 --nochroot 选项更改此行为,如下所述。
由于安装后脚本在 chroot 环境中运行,因此大多数 systemctl 命令将拒绝执行任何操作。如需更多信息,请参阅 Red Hat Enterprise Linux 7 系统管理员指南 中的" chroot 环境中的 systemctl 基准"一节
重要
如果您使用静态 IP 信息(包括名称服务器)配置了网络,则可以访问网络并解析 %post 部分中的 IP 地址。如果您为 DHCP 配置网络,安装执行 %post 部分时 /etc/resolv.conf 文件还没有完成。您可以访问网络,但无法解析 IP 地址。因此,如果您使用 DHCP,则必须在 %post 部分中指定 IP 地址。
以下选项可以用来改变安装后脚本的行为。要使用某个选项,请将其附加到脚本开头的 %post 行中。例如:
%post --interpreter=/usr/bin/python
--- Python script omitted --
%end
--interpreter=
允许指定不同的脚本语言,如 Python。例如:
%post --interpreter=/usr/bin/python
可以使用系统中可用的脚本语言;在大多数情况下,它们是 /usr/bin/sh、/ usr/bin/bash/usr/bin/python
--nochroot
允许您指定在 chroot 环境之外运行的命令。
以下示例将文件 /etc/resolv.conf 复制到刚安装的文件系统中。
%post --nochroot
cp /etc/resolv.conf /mnt/sysimage/etc/resolv.conf
%end
--erroronfail
显示错误并在脚本失败时暂停安装。错误消息会指示您记录故障原因的位置。
--log=
将脚本的输出记录到指定的日志文件中。请注意,无论您是否使用 --nochroot 选项,日志文件的路径都必须考虑。例如,没有 --nochroot:
%post --log=/root/ks-post.log
使用 --nochroot 时:
%post --nochroot --log=/mnt/sysimage/root/ks-post.log
以下是 %post 部分示例:

例 27.8. %post 脚本示例

# Start of the %post section with logging into /root/ks-post.log
%post --log=/root/ks-post.log

# Mount an NFS share
mkdir /mnt/temp
mount -o nolock 10.10.0.2:/usr/new-machines /mnt/temp
openvt -s -w -- /mnt/temp/runme
umount /mnt/temp

# End of the %post section
%end
以上示例将挂载 NFS 共享并执行位于共享中的 /usr/new-machines/ 名为 runme 的脚本。请注意,在 Kickstart 模式中 不支持 NFS 文件锁定,因此需要使用 -o nolock 选项。
Kickstart 安装中最常用的安装脚本之一就是使用 Red Hat Subscription Manager 自动注册安装的系统。以下是 %post 脚本中的自动订阅示例:

例 27.9. 将 subscription-manager 作为 Post-Install 脚本运行

%post --log=/root/ks-post.log
/usr/sbin/subscription-manager register --username=admin@example.com --password=secret --serverurl=sam-server.example.com --org="Admin Group" --environment="Dev" --servicelevel=standard --release="7.0"
%end
subscription-manager 命令行脚本将系统注册到红帽订阅管理服务器(客户门户网站订阅管理、订阅资产管理器或 CloudForms 系统引擎)。这个脚本还可用来自动在该系统中分配或者附加与该系统最匹配的订阅。
在客户门户中注册时,请使用红帽网络登录证书。在订阅资产管理器或 CloudForms 系统引擎中注册时,请使用本地管理员创建的用户帐户。
可在注册命令中使用附加选项为系统设置首选服务级别,并将更新和勘误表限制为特定的操作系统版本。