RHEL9.4上建立RockyLinux9.4虛擬機器

李蔚發表於2024-11-14

日期: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/bash

bootdev=cdrom

guestname=rocky9
guestmem=1048576
guestcups=1
hddir=/kvm/
hdsize=10G
hdpath=${hddir}${guestname}.img
vncport=5902
vncpasswd=hatred

wanmac=''
dmzmac=''
lanmac='52:54:00:10:31:01'
isopath='/data/iso/Rocky-9.4-x86_64-minimal.iso'

xmldir=/data/xml/
xmlpath=${xmldir}${guestname}.xml

qemu-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地址 RHEL9.4上建立RockyLinux9.4虛擬機器 RHEL9.4上建立RockyLinux9.4虛擬機器

系統安裝完成後重啟,仍透過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[@]} ; do
    rpm -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

相關文章