How to Run Shell Scripts with Sudo Command in Linux?

sudo is a powerful command-line tool that enables a “permitted user” to run a command as another user (the superuser by default), as defined by a security policy. On most if not all Linux systems, the security policy is driven by the /etc/sudoers file.

 

Therefore, to run a shell script or program as root, you need to use sudo command. However, sudo only recognizes and runs commands that exist in directories specified in the secure_path in the /etc/sudoers, unless a command is present in the secure_path, you’ll counter an error such as the one below.

 

This will happen even if the script exists in a directory in the PATH environmental variable, because when a user invokes sudo, PATH is replaced with secure_path.

$ echo  $PATH
$ ls  -l
$ sudo proconport.sh 80

 

In the above scenario, the directory /home/vyga/bin is in the PATH environment variable and we are trying to run the script /home/vyga/bin/proconport.sh (finds process listening on a port) with root privileges.

 

Then we encountered the error “sudo: proconport.sh: command not found”, since /home/vyga/bin is not in the sudo secure_path.

 

To fix this, we need to add the directory containing our scripts in the sudo secure_path by using the visudo command by editing /etc/sudoers file as follows.

$ sudo visudo

 

Note: This method has serious security implications especially on servers running on the Internet. This way, we risk exposing our systems to various attacks, because an attacker who manages to gain access to an unsecure (without superuser privileges) directory that has been added to secure_path, can run a malicious script/program with sudo command.

 

Preferably, we can provide the absolute path to a script while running it with sudo:

$ sudo ./proconport.sh 80

 

Was this answer helpful? 0 Users Found This Useful (0 Votes)