66 lines
1.8 KiB
Bash
Executable File
66 lines
1.8 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
read -e -p "LXCHOSTNAME: " LXCHOSTNAME
|
|
export LXCHOSTNAME
|
|
|
|
# Stop the template container
|
|
lxc-stop -n template
|
|
|
|
# Copy the template to create a new container with the given hostname
|
|
lxc-copy -n template -N "$LXCHOSTNAME"
|
|
|
|
# Function to generate a unique MAC address
|
|
generate_unique_hwaddr() {
|
|
local hwaddr
|
|
local existing_hwaddrs
|
|
while : ; do
|
|
hwaddr=$(printf '00:16:3e:%02x:%02x:%02x\n' $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256)))
|
|
existing_hwaddrs=$(grep "lxc.net.0.hwaddr" /var/lib/lxc/*/config | grep "$hwaddr")
|
|
if [ -z "$existing_hwaddrs" ]; then
|
|
# MAC address is unique
|
|
echo "$hwaddr"
|
|
return
|
|
fi
|
|
done
|
|
}
|
|
|
|
# Generate a unique MAC address
|
|
NEW_HWADDR=$(generate_unique_hwaddr)
|
|
|
|
# Path to the LXC configuration file
|
|
CONFIG_FILE="/var/lib/lxc/$LXCHOSTNAME/config"
|
|
|
|
# Replace the existing hwaddr line
|
|
sed -i "/^lxc.net.0.hwaddr/c\lxc.net.0.hwaddr = $NEW_HWADDR" "$CONFIG_FILE"
|
|
|
|
echo "MAC address in $CONFIG_FILE updated to $NEW_HWADDR."
|
|
|
|
# Start the new container
|
|
lxc-start -n "$LXCHOSTNAME"
|
|
|
|
# Wait for the container to start
|
|
sleep 5
|
|
|
|
# Change the hostname inside the container
|
|
lxc-attach -n "$LXCHOSTNAME" -- bash -c "echo '$LXCHOSTNAME' > /etc/hostname"
|
|
lxc-attach -n "$LXCHOSTNAME" -- hostname "$LXCHOSTNAME"
|
|
|
|
# Update /etc/hosts
|
|
lxc-attach -n "$LXCHOSTNAME" -- bash -c "echo '127.0.0.1 $LXCHOSTNAME' >> /etc/hosts"
|
|
|
|
# Ensure the container has internet access (optional, check and adjust if needed)
|
|
lxc-attach -n "$LXCHOSTNAME" -- ping -c 4 google.com
|
|
echo
|
|
|
|
# Stop and restart the container
|
|
lxc-stop -n "$LXCHOSTNAME"
|
|
lxc-start -n "$LXCHOSTNAME"
|
|
|
|
# Display the MAC addresses to verify the changes
|
|
grep lxc.net.0.hwaddr /var/lib/lxc/*/config
|
|
|
|
# Wait and list containers to ensure they are running
|
|
sleep 9
|
|
lxc-ls -f
|
|
|