0

I know this will sound naive to most of you, but I'm still new in Linux so please bear with me.

I am trying to create a batch file in order to automate a few commands.
One of those commands is the sudo -i since I need to access some files in root.

So my script so far looks like this:

#!/bin/bash
sudo -i
cd my-server/bin
./run-server.sh

I know that after sudo -i follows a prompt for password, so can I emulate that in my script?

0

2 Answers 2

1

You can take sudo out of your script and ensure users call the script using sudo scriptname.

Remove sudo -i line from your script and replace it with this:

# Must prefix with sudo when calling script
if ! [[ $(id -u) == 0 ]]; then
    echo You must call this script using sudo. Aborting.
    exit 99
fi
1
  • I like this approach, this way I avoid keeping my password it text like @DmC8pR2kZLzdCQZu3v mentioned.
    – user976971
    Nov 16, 2019 at 8:02
1

Fair question. But its is strongly advisable that you don't go about this the way that you are currently attempting/envisioning it. The reason to avoid your approach is that it requires entering your password into a text file that could be read by other users/attackers. Now, you could set the file to 600 permissions so that it can only be read by your user (and root), but I'm not sure if the scripts sub-commands may be logged somewhere, making your password again available to potential attackers. I suppose the real question is, why do you need the script to log in as root automatically?

Is it an automated process, or is there some other reason you can't simply respond to the password prompt that is presented when running the script as is? If it's an automated process, you should simply remove the sudo line and add the script call to the root users cron. There is tons of documentation on how to set up cron jobs available by a simple google search, but you can get started with this)

Furthermore, this is a script that simply calls another script. You should probably just make run-server.sh only executable by root, then simply use sudo su to log into root, then run it with /my-server/bin/run-server.sh. Again, you could add this to the root's cron if you need to automate it on a schedule.

WARNING: Don't script this, and especially don't type it on a command line (it will be logged)

echo 'PASSWORD' | sudo -S /my-server/bin/run-server.sh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy