Automating Nopasswd Sudoers User Switch in Shell Scripts

How to Automating User Switch in Shell Scripts with Nopasswd Sudoers

Shell scripts help make system administration tasks easier. However, securely running commands as different users can be a challenge. we explore sudo with Nopasswd Sudoers to switch users and execute commands safely.

Objective :

  • secure switch users and run commands using sudo.
  • Users run commands without passwords in the sudoers file.

Prerequisites :

  • Basic understanding of shell scripting.
  • Familiarity with the sudo command and sudoers file.
  • Access the UNIX-based system eg LINUX

Note :

  • Navigate to the directory where the script is located.
  • you can change the user name to your requirement 
  • Understand each command before executing the script to ensure it fits your environment and requirements.

Nopasswd Sudoers Action plan :

Step 1:

Open the terminal and connect to the root user

sudo su –

Step 2 :

Edit the ‘sudoers’ file in the etc directory use the below command

vi /etc/sudoers

Add the below lines to the file 

oracle ALL=(apps) NOPASSWD: ALL
oracle ALL=(root) NOPASSWD: ALL

This configuration allows the Oracle user to switch to apps and root without a password.

Script sample outputs :

Excuted the script

output of the script

 

User Switch in Shell Scripts with Nopasswd Sudoers :

#################################################################
# Date: 10-June-2024
# Author: Krishna Tummeti
# Website: Tech Base Hub
# Purpose: Switch the user and execute the commands or scripts
#################################################################

# Switch to 'apps' user, and execute the commands.

echo "Switching to 'apps' user..."
sudo su - apps -c '
echo "This is the apps user-id"
whoami
id
' > /tmp/id_output.txt

# Switch to 'root' user, and execute the commands.

echo "Switching to 'root' user..."
sudo su - root -c '
echo "This is the root user-id"
whoami
id
' >> /tmp/id_output.txt

# Move the file from /tmp to /home/oracle/krishna and set permissions

sudo mv /tmp/id_output.txt /home/oracle/krishna/id_output.txt
sudo chown oracle:oracle /home/oracle/krishna/id_output.txt

# Execute the id command as Oracle user and append the output to the same file

echo ""
echo "Running id command as Oracle user..."
echo "This is the Oracle user-id" >> /home/oracle/krishna/id_output.txt
id >> /home/oracle/krishna/id_output.txt

echo "The Script is completed."

We have successfully executed the ‘Nopasswd Sudoers’ script for passwordless user switching. 

Thank you

Leave a Comment