Below is a shell script that creates a new user and adds their SSH public key to an Ubuntu VM:
#!/bin/bash
# Function to create a new user and add SSH public key
create_user_and_add_ssh_key() {
username=$1
ssh_key_path=$2
# Create user
sudo adduser --disabled-password --gecos "" $username
# Create .ssh directory if not exists
sudo -u $username mkdir -p /home/$username/.ssh
# Copy SSH public key to authorized_keys file
cat $ssh_key_path >> /home/$username/.ssh/authorized_keys
# Set proper permissions
sudo chown -R $username:$username /home/$username/.ssh
sudo chmod 700 /home/$username/.ssh
sudo chmod 600 /home/$username/.ssh/authorized_keys
}
# Example usage
new_username="newuser"
ssh_key_path="/path/to/public_key.pub"
create_user_and_add_ssh_key $new_username $ssh_key_path
Make sure to replace newuser with the desired username and /path/to/public_key.pub with the path to the SSH public key file you want to add.
Save this script to a file (e.g., create_user_and_add_ssh_key.sh), make it executable (chmod +x create_user_and_add_ssh_key.sh), and then run it (./create_user_and_add_ssh_key.sh).
This script will create a new user without a password prompt and add their SSH public key to the authorized_keys file.