DEV Community

Cover image for Bash script that helps you set up server configurations, create users, and set permissions
Muzaffar khan
Muzaffar khan

Posted on

Bash script that helps you set up server configurations, create users, and set permissions

Certainly! An example of a Bash script that may be used to configure servers, create users, and establish permissions is provided below. Please exercise caution when running scripts that create or edit user accounts or alter server configurations. Check the script again and make any necessary adjustments.

**

Certainly! Here's an example of a Bash script that automates server provisioning using the ssh command.

**

#!/bin/bash

server_ip="your_server_ip"
server_user="your_username"
server_ssh_port=22


remote_commands=(
    "sudo apt update && sudo apt upgrade -y"
    "sudo apt install -y nginx"
    "sudo systemctl start nginx"
    "sudo systemctl enable nginx"
)

for command in "${remote_commands[@]}"; do
    ssh "$server_user"@"$server_ip" -p "$server_ssh_port" "$command"
    if [ $? -eq 0 ]; then
        echo "Command executed successfully: $command"
    else
        echo "Command failed: $command"
        exit 1
    fi
done

echo "Server provisioning completed."
Enter fullscreen mode Exit fullscreen mode

**

Certainly! Below is an example of a Bash script that helps you set up, create users, and set permissions.

**

#!/bin/bash

create_user() {
    username=$1
    password=$2

    sudo useradd -m -s /bin/bash $username
    echo "$username:$password" | sudo chpasswd    
    echo "User $username created successfully."
}

setup_ssh() {
    username=$1

    sudo -u $username ssh-keygen -t rsa -b 4096 -f /home/$username/.ssh/id_rsa -N ""

    sudo -u $username sh -c "cat /home/$username/.ssh/id_rsa.pub >> /home/$username/.ssh/authorized_keys"

    sudo chmod 700 /home/$username/.ssh
    sudo chmod 600 /home/$username/.ssh/id_rsa
    sudo chmod 644 /home/$username/.ssh/id_rsa.pub
    sudo chmod 644 /home/$username/.ssh/authorized_keys

    sudo chown -R $username:$username /home/$username/.ssh

    echo "SSH access set up for user $username."
}

if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root or with sudo."
    exit 1
fi

read -p "Enter the username for the new user: " new_username
read -s -p "Enter the password for the new user: " new_password
echo

create_user $new_username $new_password
setup_ssh $new_username

echo "User account setup complete."


Enter fullscreen mode Exit fullscreen mode

Top comments (0)