Rocky Linux 9.1 Sysprep Script

Posted on January 16 2023 under linux and bash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

# Stop logging services
echo "Stopping logging service..."
systemctl stop rsyslog

# Rotate and clear old logs
echo "Cleaning up log files..."
logrotate -f /etc/logrotate.conf
rm -f /var/log/*-????????
rm -f /var/log/*.gz
rm -f /var/log/dmesg.old
rm -rf /var/log/anaconda
rm -f /root/anaconda-ks.cfg
cat /dev/null > /var/log/audit/audit.log
cat /dev/null > /var/log/wtmp
cat /dev/null > /var/log/lastlog
cat /dev/null > /var/log/grubby

# Clear old kernels
echo "Cleaning up old kernels..."
package-cleanup -y --oldkernels --count=1 > /dev/null 2>&1

# Clear dnf cache
echo "Cleaning up dnf cache..."
dnf -y clean all > /dev/null 2>&1

# Clear udev hardware rules
echo "Cleaning up udev rules..."
rm -f /etc/udev/rules.d/*

# Clear machine ID
echo "Unsetting machine ID..."
rm -f /etc/machine-id

# Clear SSH host keys
echo "Cleaning up SSH keys..."
rm -f /etc/ssh/*key*

# Clear users' shell history
echo "Cleaning up BASH history..."
rm -f /root/.bash_history
rm -f /home/*/.bash_history
unset HISTFILE

# Clear users' SSH history
echo "Cleaning up SSH history..."
rm -rf /root/.ssh/
rm -rf /home/*/.ssh/

# Set up MOTD
echo "Configuring MOTD..."
cat >/etc/motd <<EOL

Welcome to Rocky Linux 9.1!

To complete the installation:
    # sudo systemd-machine-id-setup
    # sudo hostnamectl set-hostname <hostname>.<domainname>
    # sudo nmcli connection modify ens3 ipv4.address1 10.x.x.x/24,10.x.x.1
    # sudo nmcli networking off && sudo nmcli networking on
    # sudo dnf -y update

To show this message again, run:
    # cat /etc/motd

To stop this message from displaying, run:
    # sudo sh -c 'echo -n > /etc/motd'

EOL

# Finish
rm -f /root/sysprep.sh
echo "Done! Please power off before making a snapshot"