Systemd gives us a utility to change hostname with
https://www.freedesktop.org/software/systemd/man/hostnamectl.html
Inspiration taken from here -->
https://github.com/red0xff/hostnamespoof
Here is my code -->
File location: /usr/local/bin/rand_hostname.sh
#!/bin/bash
#Generate a random string and then use it as a hostname. Used in conjunction with randomising the
#network adapter MAC addresses to help keep you anonymous
#Generates a random string between 3 and 9 chars
hostname=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c$(< /dev/urandom tr -dc 3-9 | head -c1;echo;);echo;)
#Debug
#echo $hostname
#now set the new hostname
/usr/bin/hostnamectl set-hostname $hostname
Now to set up the systemd service.
File location: /etc/systemd/system/rand_hostname.service
[Unit]
Description=a tool randomizing hostname at each boot
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/rand_hostname.sh
[Install]
WantedBy=multi-user.target
Now to enable with
sudo systemctl enable rand_hostname.service
And reload
sudo systemctl daemon-reload rand_hostname.service