Approach 1 - Read from file
You can save the password in a read-only file for the user and pass the contents to the sudo command.
This will avoid password being stored in shell history
# Save the password in the hidden file
echo "password" > ~/.password
Update the permissions to allow only the user to read it
chmod 400 ~/.password
Pass the password over STDIN to sudo
☠ cortex ☠ [~] cat ~/scripts/login_file.sh
cat ~/.password | sudo -S su
Execute the script
☠ cortex ☠ [~] bash ~/scripts/login_file.sh
[sudo] password for cortex:
☠ cortex ☠ [~]
Approach 2 - Save to temporary environment variable
With this approach, you need to enter on the shell or in the script.
☠ cortex ☠ [~] cat ~/scripts/login.sh
my_password='password' # SET PASSWORD
echo "$my_password" | sudo -S su # INVOKE sudo WITH PASSWORD
Combine with the script
Use any of the approaches mentioned above and authenticate sudo
Then invoke the commands with root access.
☠ cortex ☠ [~] cat ~/scripts/login.sh
# SET PASSWORD
my_password='password'
INVOKE sudo WITH PASSWORD
echo "$my_password" | sudo -S su;
INVOKE COMMANDS WITH ROOT ACCESS
sudo -i <<'EOF'
echo "Now i am $(whoami)"
echo "$(id)"
EOF
☠ cortex ☠ [~] bash ~/scripts/login.sh
[sudo] password for cortex: Now i am root
uid=0(root) gid=0(root) groups=0(root)
Cut the clutter with ALIAS
Make the sudo to internally get the password and authenticate itself.
You need not require to input the password over STDIN every time
# Create the alias with the Approach 1
☠ cortex ☠ [~] echo "alias sudo=\"cat ~/.password | sudo -S\"" >> ~/.bashrc
OR Create the alias with the Approach 2
☠ cortex ☠ [~] echo "alias sudo="echo "password" | sudo -S"" >> ~/.bashrc
Re-load the environment
☠ cortex ☠ [~] . ~/.bashrc
Use sudo directly - No need to pass on password everytime
☠ cortex ☠ [~] sudo whoami
root