日期:2024.11.13
计划:在LANbridge网段里安装RockyLinux9.4虚拟机,IP地址10.31.0.1,用于搭建dhcp服务器
参照:
- 鸟哥Linux私房菜
- 马哥教育王晓春老师课程
TOPO结构如图
之前安装rhle8的时候写了自动化安装的脚本,现在只需要简单修改一下再执行,无需手动编辑xml文件,就可以创建虚拟机了。
创建虚拟机的脚本
[root@RHEL9 ~]# cat rocky9create-cd.sh
#guestcreate.sh
#Date: 2024-11-08
#!/bin/bashbootdev=cdromguestname=rocky9
guestmem=1048576
guestcups=1
hddir=/kvm/
hdsize=10G
hdpath=${hddir}${guestname}.img
vncport=5902
vncpasswd=hatredwanmac=''
dmzmac=''
lanmac='52:54:00:10:31:01'
isopath='/data/iso/Rocky-9.4-x86_64-minimal.iso'xmldir=/data/xml/
xmlpath=${xmldir}${guestname}.xmlqemu-img create -f qcow2 ${hdpath} ${hdsize}cat > ${xmlpath} << EOF
<domain type="kvm"><name>${guestname}</name><uuid>$(uuidgen)</uuid><memory>${guestmem}</memory><vcpu>${guestcups}</vcpu><os><type arch="x86_64" machine="q35">hvm</type><boot dev="hd"/></os><features><acpi/><apic/></features><cpu mode="host-passthrough"/><clock offset="utc"><timer name="rtc" tickpolicy="catchup"/><timer name="pit" tickpolicy="delay"/><timer name="hpet" present="no"/></clock><pm><suspend-to-mem enabled="no"/><suspend-to-disk enabled="no"/></pm><devices><emulator>/usr/libexec/qemu-kvm</emulator><disk type="file" device="disk"><driver name="qemu" type="qcow2" discard="unmap"/><source file="${hdpath}"/><target dev="vda" bus="virtio"/></disk><controller type="usb" model="qemu-xhci" ports="15"/><controller type="pci" model="pcie-root"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><console type="pty"/><channel type="unix"><source mode="bind"/><target type="virtio" name="org.qemu.guest_agent.0"/></channel><input type="tablet" bus="usb"/><graphics type="vnc" port="${vncport}" listen="0.0.0.0" passwd="${vncpasswd}"/><video><model type="virtio"/></video><memballoon model="virtio"/><rng model="virtio"><backend model="random">/dev/urandom</backend></rng></devices>
</domain>
EOF[[ -n ${bootdev} ]] && sed -Ei.bak '/ <boot dev="hd"\/>/a \ <boot dev="'''${bootdev}'''"\/>' ${xmlpath}
[[ -n ${isopath} ]] && sed -Ei '/ <controller type="usb" model="qemu-xhci" ports="15"\/>/i \ <disk type="file" device="cdrom">\n <driver name="qemu" type="raw"\/>\n <source file="'''${isopath}'''"\/>\n <target dev="sda" bus="sata"\/>\n <readonly\/>\n <\/disk>' ${xmlpath}
[[ -n ${wanmac} ]] && sed -Ei '/ <console type="pty"\/>/i \ <interface type="bridge">\n <source bridge="WANbridge"/>\n <mac address="'''${wanmac}'''"\/>\n <model type="virtio"\/>\n <\/interface>' ${xmlpath}
[[ -n ${dmzmac} ]] && sed -Ei '/ <console type="pty"\/>/i \ <interface type="bridge">\n <source bridge="DMZbridge"/>\n <mac address="'''${dmzmac}'''"\/>\n <model type="virtio"\/>\n <\/interface>' ${xmlpath}
[[ -n ${lanmac} ]] && sed -Ei '/ <console type="pty"\/>/i \ <interface type="bridge">\n <source bridge="LANbridge"/>\n <mac address="'''${lanmac}'''"\/>\n <model type="virtio"\/>\n <\/interface>' ${xmlpath}virsh create ${xmlpath}
脚本生成的虚拟机配置文件rocky9.xml
[root@RHEL9 ~]# cat /data/xml/rocky9.xml.bak
<domain type="kvm"><name>rocky9</name><uuid>7999d09f-2b8a-441f-a205-ad31c4f0eb9c</uuid><memory>1048576</memory><vcpu>1</vcpu><os><type arch="x86_64" machine="q35">hvm</type><boot dev="hd"/><boot dev="cdrom"/></os><features><acpi/><apic/></features><cpu mode="host-passthrough"/><clock offset="utc"><timer name="rtc" tickpolicy="catchup"/><timer name="pit" tickpolicy="delay"/><timer name="hpet" present="no"/></clock><pm><suspend-to-mem enabled="no"/><suspend-to-disk enabled="no"/></pm><devices><emulator>/usr/libexec/qemu-kvm</emulator><disk type="file" device="disk"><driver name="qemu" type="qcow2" discard="unmap"/><source file="/kvm/rocky9.img"/><target dev="vda" bus="virtio"/></disk><disk type="file" device="cdrom"><driver name="qemu" type="raw"/><source file="/data/iso/Rocky-9.4-x86_64-minimal.iso"/><target dev="sda" bus="sata"/><readonly/></disk><controller type="usb" model="qemu-xhci" ports="15"/><controller type="pci" model="pcie-root"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><interface type="bridge"><source bridge="LANbridge"/><mac address="52:54:00:10:31:01"/><model type="virtio"/></interface><console type="pty"/><channel type="unix"><source mode="bind"/><target type="virtio" name="org.qemu.guest_agent.0"/></channel><input type="tablet" bus="usb"/><graphics type="vnc" port="5902" listen="0.0.0.0" passwd="hatred"/><video><model type="virtio"/></video><memballoon model="virtio"/><rng model="virtio"><backend model="random">/dev/urandom</backend></rng></devices>
</domain>
安装过程中手动配置IP地址
系统安装完成后重启,仍通过vnc连接,登录系统后运行一个初始化环境配置的脚本。主要功能包括安装常用软件,关闭无关服务,优化系统,配置环境等。
初始化环境配置脚本
[root@centos7 ~]# cat /file/SH/envinit.sh
#environmentinit.sh
#Date: 2024-10-30
#!/bin/bash#设置颜色代码
black='\[\e[1;30m\]'
red='\[\e[1;31m\]'
green='\[\e[1;32m\]'
yellow='\[\e[1;33m\]'
blue='\[\e[1;34m\]'
pink='\[\e[1;35m\]'
cyan='\[\e[1;36m\]'
white='\[\e[1;37m\]'
endcolour='\[\e[0m\]'#用sed抓出hostnamectl指令中的发行版名称
distribution=$(hostnamectl | sed -En 's/^[[:blank:]]*Operating System\: +(.+)$/\1/p')#运行脚本时如果加参数可以手动指定发行版本
[[ -n ${1} ]] && distribution=${1}#根据不同的发行版本设置不同的命令提示符颜色
case ${distribution} in
'Red Hat Enterprise Linux'* | rhel* )echo PS1=\""${red}[\u@\h \W]\\\\\$${endcolour} "\" > /etc/profile.d/environment.sh;;
'CentOS Linux'* | centos* )echo PS1=\""${pink}[\u@\h \W]\\\\\$${endcolour} "\" > /etc/profile.d/environment.sh;;
'Rocky Linux'* | rocky* )echo PS1=\""${green}[\u@\h \W]\\\\\$${endcolour} "\" > /etc/profile.d/environment.sh
esac#安装常用软件
which mail || yum -y install s-nail || yum -y install mailx
package_name=("bash-completion" "vim-enhanced" "tuned")
for package in ${package_name[@]} ; dorpm -q ${package} || yum -y install ${package}done#创建常用环境启动脚本:1.历史记录显示日期时间 2.默认文本编辑器为vim
cat << EOF >> /etc/profile.d/environment.sh
HISTTIMEFORMAT="%F %T "
export EDITOR=/usr/bin/vim
set -C
EOF#设置vim配置文件:1.行号 2.自动缩进 3.扩展tab键 4.一下tab等于4个空格 5.语法颜色
echo "set number
set autoindent
set expandtab
set tabstop=4
syntax on" | tee /root/.vimrc > /dev/null#调用vim函数设置sh脚本备注:1.脚本名字 2.创建日期 3.#!/bin/bash 4.空一行
cat <<EOF | tee -a /root/.vimrc >> /dev/null
autocmd BufNewFile *.sh exec ":call SetTitle()"
func SetTitle()if expand("%:e") == 'sh'call setline(1,"#".expand("%"))call setline(2,"#Date: ".strftime("%Y-%m-%d"))call setline(3,"#!/bin/bash")call setline(4,"")endif
endfunc
autocmd BufNewFile * normal G
EOF#写入mail发信配置文件
echo "set from=XXXXX@XX.com
set smtp=smtp.163.com
set smtp-auth-user=XXXXX@XX.com
set smtp-auth-password=XXXXX
set smtp-auth=login
set ssl-verify=ignore" | tee /root/.mailrc > /dev/null#写入常用公钥
[ -d /root/.ssh ] || mkdir -p /root/.ssh
echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDDatyT4rkUtIASwqIlM5cHq8A6coBAdJr8FQgy8t2qUL9M/0TjirRX4qORRbJyW6F3nMf94ZIkp15LStcFA8miOpUC/eh6xLof/sHxjTvP06giT3j05w7G2UZlFptflU97flXwsBTD+XAltjpdWDcw0B/ig7NJS6v3zgmhqtnD018tRe9GKLKiEjMmpCmqIBeu+sShWJbhBuGXzETPHSvHZK1kLnVgHWPZ+5dMr/c4djahYMC2NycYtye8+6EaibaIc9DDWz8yRQigQDsFm/PKG+ys9nPYyhEMoW6toiTQKvngvdkVPp3XXF5jakPgFs474AyBlTy0fB5yagLx4C8S9grpbHBEjXSN6Nas/ruPGojjvWZCB13gGkGScuFvkN4KRmlOiRMJGZmy8Jqp3FxCpwkt5fEMHfM0yE+n/hYoW+emJAmKpRIWcmos4vO35XiXai0OAotG/XHaIzAXEsAYaqQSkQLEg2jDQiEbPJH1LXURYAo6NPxynHvZYOve7W8= root@RHEL9' > /root/.ssh/authorized_keys
echo 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA4eO1CtS30eODMchvV9MDd7opc5B5Q3gDu45mJJxSfNrL9PU17xp0MS+LpXE12Subl4cT566kB2HD2Lu4e7DYBiGSShqQriY+l+f3Tp7/JoDEd9bDZeVsu0henqz7ZBPJ7LQYjC8Kg4VYb5kOJvhm4dqOyT2eyxc9TjXwHXu5vhKMoEluLD3CQu18YTzFsOhpMbes7OvG8pMtFSsEYzRrAUMW0MQ6qhwFfdoXoVolyR66MY8zH/ADjlJI/agQnNnL5/B9ZveseqGJJUvIR6F4GZpLQDJkWcTYupbUt7WpqzJbmms7Ohe5tyKjcQrukwT3IW4iIG6L9mYEC7APOcdfzQ== rsa 2048-082324' >> /root/.ssh/authorized_keys
echo 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA9LCZtZ9a74PcEsTt6s3nFN8oIXxsYrcePec7zYZH9ygh+aiE6DieQPWlPmVTqfD4QNO+2ni9oA/QdnLaMn9k8tUO2kLJ8JySbh/8tpnWSQQs4TkD1Hs1Rw3/j1pUXpsldkHSe+epdUwQokvyeII/+vMsE507MkeOhyZrc3tZgRPSfxxsyPeIyhYeq+pDYF0+MLj8vkcEEJ8AD0FonQNeflROJ60e2RYrwkJnMd6lQw/naQtJJ1E6/0pMxnMdRpO7K3Q8y8BVo2G/KfaAWbQEAG1HiA5HBUIOVw6+tWYOJ0wQFe7u2PEra2kfeVYluVML6ajHu9p1phmrZ6O3S2LsAw== rsa 2048-082624' >> /root/.ssh/authorized_keys#禁止root密码登陆
sed -Ei.bak 's/^#?(PermitRootLogin).+$/\1 prohibit-password/' /etc/ssh/sshd_config
systemctl reload sshd.service#关闭防火墙无关服务
firewall-cmd --permanent --remove-service={cockpit,dhcpv6-client}
firewall-cmd --reload#启用tuned调优
systemctl enable --now tuned.service
tuned-adm profile $(tuned-adm recommend)#写入计划任务
#1.自动拉黑每小时登录失败超过指定次数的IP
cat << EOF >> /var/spool/cron/root
0 * * * * /usr/bin/lastb | /usr/bin/awk -v hourago="\$(/usr/bin/date --date='1 hour ago' '+\%a \%b \%e \%H:')" '\$0~hourago{ip[\$3]++}END{for (i in ip){if(ip[i]>11){system("/usr/bin/firewall-cmd --add-source="i" --zone=block;/usr/bin/firewall-cmd --runtime-to-permanent;/usr/bin/echo \"\$(/usr/bin/hostname) ban "i" for connected "ip[i]" times in 1 hour\" >> /tmp/baninfo")}}}';[ -e /tmp/baninfo ] && /usr/bin/cat /tmp/baninfo | /usr/bin/mail -s "Ban Info" XXXXX@XX.com && /usr/bin/rm -f /tmp/baninfo
EOF
初始化环境配置完成后,在vnc里关闭虚拟机。执行定义虚拟机的脚本,删除多余启动项和光驱,设置虚拟机开机自启。
定义虚拟机的脚本
[root@RHEL9 ~]# cat rocky9define-cd.sh
#guestdefine.sh
#Date: 2024-11-09
#!/bin/bash#配置文件位置
xmlpath=/data/xml/rocky9.xml
guestname=$(sed -En 's/<name>(rocky9)<\/name>/\1/p' ${xmlpath})#删除vnc远程连接
sed -Ei.bak '/<graphics type="vnc" port=/d' ${xmlpath}#删除启动项cdrom
sed -Ei '/<boot dev="cdrom"\/>/d' ${xmlpath}#删除设备cdrom
sed -Ei '/<disk type="file" device="cdrom">/,/<\/disk>/d' ${xmlpath}#定义虚拟机
virsh define ${xmlpath}#启动虚拟机
virsh start ${guestname}#设置虚拟机开机启动
virsh autostart ${guestname}
定义后的rocky9.xml文件
[root@RHEL9 ~]# cat /data/xml/rocky9.xml
<domain type="kvm"><name>rocky9</name><uuid>7999d09f-2b8a-441f-a205-ad31c4f0eb9c</uuid><memory>1048576</memory><vcpu>1</vcpu><os><type arch="x86_64" machine="q35">hvm</type><boot dev="hd"/></os><features><acpi/><apic/></features><cpu mode="host-passthrough"/><clock offset="utc"><timer name="rtc" tickpolicy="catchup"/><timer name="pit" tickpolicy="delay"/><timer name="hpet" present="no"/></clock><pm><suspend-to-mem enabled="no"/><suspend-to-disk enabled="no"/></pm><devices><emulator>/usr/libexec/qemu-kvm</emulator><disk type="file" device="disk"><driver name="qemu" type="qcow2" discard="unmap"/><source file="/kvm/rocky9.img"/><target dev="vda" bus="virtio"/></disk><controller type="usb" model="qemu-xhci" ports="15"/><controller type="pci" model="pcie-root"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><controller type="pci" model="pcie-root-port"/><interface type="bridge"><source bridge="LANbridge"/><mac address="52:54:00:10:31:01"/><model type="virtio"/></interface><console type="pty"/><channel type="unix"><source mode="bind"/><target type="virtio" name="org.qemu.guest_agent.0"/></channel><input type="tablet" bus="usb"/><video><model type="virtio"/></video><memballoon model="virtio"/><rng model="virtio"><backend model="random">/dev/urandom</backend></rng></devices>
</domain>
在搭建rhle8路由的时候端口的转发规则都已经配置好,ssh直接发起远程连,登录成功,修改主机名
Connecting to 221.229.XX.X1:62223...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.WARNING! The remote SSH server rejected X11 forwarding request.
Last login: Wed Nov 13 05:57:40 2024 from 112.2.XX.XX
[root@localhost ~]# clear
[root@localhost ~]# hostnamectl set-hostname ROCKY9