Thursday, February 02, 2023

Script to add a new user on server

 Write a script to login to Ubuntu server via SSH and add a new user called deploy and give it a password called secret.

Here is a script in Bash that logs in to an Ubuntu server via SSH, adds a new user deploy, and sets a password for it:

#!/bin/bash


# Variables for the remote server login and new user information

user=<username>

server=<server_ip_or_hostname>

new_user=deploy

password=secret


# Connect to the remote server using SSH

ssh $user@$server << EOF

    # Switch to the root user

    sudo su


    # Add the new user

    adduser $new_user


    # Set the password for the new user

    echo "$new_user:$password" | chpasswd

EOF


Replace the placeholders <username>, <server_ip_or_hostname> with the appropriate values for your setup. Then, save the script to a file and make it executable with the chmod +x command. You can then run the script from the terminal.


Note that this script assumes that you have SSH access to the server with a user account that has sudo privileges. Also, be careful when using this script, as it adds a new user and sets a password, which can have security implications. Make sure to test the script in a safe environment before using it in production.