Linux run command with user

Running Script or Command as Another User in Linux

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

1. Overview

In this tutorial, we’ll learn different ways of running scripts or commands as another user in Linux. In particular, we’ll see how we can do that without logging in as the target user.

2. Environment

Let’s assume that in addition to root, there are user annie and user dave in our system as well. Then, while logged in as annie, we create a script annie-script.sh in /home/annie:

$ cat > /home/annie/annie-script.sh 

In the script, we first obtain the username with the whoami command. This will capture the username of the user executing the script. Then, we use process substitution to combine the username with the message to be printed. Finally, the echo will print the entire message to standard output.

With this simple script, we’ll be able to tell which user runs the script.

Additionally, we make the script executable by annie only:

$ chmod u+x /home/annie/annie-script.sh

We can then verify the permission information of the script:

$ ls -l /home/annie total 4 -rwxrw-r-- 1 annie annie 41 Oct 31 03:11 annie-script.sh

From the file permission bits, we can see that only the owner can execute that script. In our example, only annie can execute the script. In other words, the only way dave can execute annie-script.sh is through annie.

Once the environment is set up, we’ll log in again as dave.

In the following sections, we’ll demonstrate how to run annie-script.sh as annie, while stay logged in as dave.

3. Using su

su is a command-line tool that is commonly used to switch users in Linux. Additionally, it also allows us to execute scripts or commands as another user.

3.1. Running Script as Another User

While logged in as user dave, we can run the annie-script.sh as user annie:

$ su -c '/home/annie/annie-script.sh' annie Password: Running annie-script.sh as user annie

By default, the su command takes an input a target username to switch into. However, we can specify a script to be run with the flag -c. When specified, su command will just execute the script without dropping into a new shell as the target user.

In our example, we use the su command to execute the annie-script.sh with user annie. Then, su command will ask for annie‘s password. Once authenticated, the script will be executed.

From the output, we can see that the script is indeed executed by annie as indicated by our simple script.

Without specifying a target user, su command will switch into root instead:

$ su -c 'echo I am $(whoami)' Password: Running annie-script.sh as user root

3.2. Disabling the Password Prompt

The password prompt might not always be preferable, especially during scripting. As the su command relies on Linux’s PAM for authentication purposes, we can disable the password prompt for the su command through its PAM configuration file.

Let’s disable the password prompt when user dave is executing scripts as user annie.

Firstly, we open up the file /etc/pam.d/su with any text editor. Then, we’ll add the following lines into the file right after the line auth sufficient pam_rootok.so:

auth [success=ignore default=1] pam_succeed_if.so user = annie auth sufficient pam_succeed_if.so use_uid user = dave

The first rule checks if the target user is annie. If it is, then it’ll proceed with the second rule to check if the current user is dave. If both rules evaluate to true, permission will be granted, and dave can use su without having to input annie‘s password.

On the other hand, if either one of the rules fails, it will transparently ignore these rules, prompting for a password.

Once configured, we can now run the same command without the password prompt:

$ su -c /home/annie/annie-script.sh annie Running annie-script.sh as user annie

However, if we try to run the same command as user root, su will ask for the root‘s password. That’s because the password exemptions for dave only applies when he is executing scripts as annie, not as anyone else.

4. Using sudo

sudo is another command-line tool that allows users to execute scripts as another user. In this article, we’ll be skipping the details about the sudo command. Instead, we’ll focus on utilizing sudo to execute scripts as another user.

4.1. Running a Specific Script as Another User

Before we can execute scripts as other users with sudo, we’ll need to add the current user to the sudoers file. To do that, we’ll use the visudo command to safely edit the /etc/sudoers file.

Let’s add dave into sudoers file by executing the following command as root:

$ echo 'dave ALL=(annie) /home/annie/annie-script.sh' | EDITOR='tee -a' visudo

The command above echo the rule and pipe the rule into the visudo command. By default, visudo will open up an interactive editor. However, we’ve overridden that behavior through the EDITOR field. Finally, visudo will append the rules into the sudoers file using the command tee -a.

The rule grants dave the permission to execute the script annie-script.sh as user annie on any hosts.

After the configuration, we can execute annie-script.sh as annie with sudo command while logged in as dave:

$ sudo -u annie /home/annie/annie-script.sh [sudo] password for dave: Running annie-script.sh as user annie

The sudo command takes as an argument the command or script to execute. Additionally, the flag -u can be specified to change the target user from the default root into another user.

Notice that with sudo, it requests for the current user’s password instead of the target user. Once authenticated, we’ll see that the script has indeed been executed as annie.

4.2. Running Scripts as Any Users on the System

If we now run the command as root, we’ll see the following output:

$ sudo -u root /home/annie/annie-script.sh [sudo] password for dave: Sorry, user dave is not allowed to execute '/home/annie/annie-script.sh' as root

Because the rules we’ve configured only allow dave to execute annie-script.sh (a specific script) as annie (a specific user). To allow dave to execute the script annie-script.sh as any users, we can change the rules for dave as such:

dave ALL=(ALL) /home/annie/annie-script.sh

With the value ALL instead of annie, dave will be able to execute annie-script.sh as any users on the system.

Once we’ve re-configured it, we’ll be able to run the same command successfully:

$ sudo -u root /home/annie/annie-script.sh [sudo] password for dave: Running annie-script.sh as user root

4.3. Skipping Password Prompt

With sudo, we can also disable the password prompt by prefixing NOPASSWD in front of the script and command section.

For example, we can disable the password prompt for dave by tweaking the rules:

dave ALL=(ALL) NOPASSWD: /home/annie/annie-script.sh

In the rules, we’ve prepended NOPASSWD in front of the script. That’ll exempt dave from the password input request when he is running annie-script.sh as another user.

After reconfiguring, we can re-run the command as both annie and root without having to input dave‘s password:

$ sudo -u annie /home/annie/annie-script.sh Running annie-script.sh as user annie $ sudo -u root /home/annie/annie-script.sh Running annie-script.sh as user root

5. Conclusion

In this tutorial, we’ve first started by setting up an environment for this tutorial.

Then, we saw how we could use the su command to execute a script as other users. We’ve taken a step further to disable the password prompt by modifying the PAM configuration file.

Next, we’ve demonstrated the same functionality with the sudo command. Finally, we’ve also seen how we can skip the password prompt from sudo by configuring the sudoers file using visudo.

Источник

How to run a command as a specific user in an init script?

I'm writing an init script which is supposed to execute a single command as a user different than root. This is how I'm doing it currently:
sudo -u username command This generally works as expected on Ubuntu/Debian, but on RHEL the script which is executed as the command hangs.
Is there another way to run the command as another user?
(Note that I can't use lsb init functions as they're not available on RHEL/Centos 5.x.)

Notice that this question is about something set up exclusively by the administrator (typically, a daemon that runs as some user for security). A slightly different case is users setting up on their own commands to run at boot, with their user crontab. See askubuntu.com/questions/260845/…

6 Answers 6

On RHEL systems, the /etc/rc.d/init.d/functions script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.

The specific function provided to help with this is daemon . If you are intending to use it to start a daemon-like program, a simple usage would be:

daemon --user=username command 

If that is too heavy-handed for what you need, there is runuser (see man runuser for full info; some versions may need -u prior to the username):

/sbin/runuser username -s /bin/bash -c "command(s) to run as user username" 

Источник

Run a shell script as another user that has no password

I would like to run a script from the main ubuntu shell as a different user that has no password. I have full sudo privileges, so I tried this:

sudo su -c "Your command right here" -s /bin/sh otheruser 

Then I have to enter my password, but I am not sure if that script is now really running under that user. How can I confirm that the script is really running under that user now?

10 Answers 10

You can do that with su or sudo , no need for both.

sudo -H -u otheruser bash -c 'echo "I am $USER, with uid $UID"' 

The relevant parts of man sudo :

-H The -H (HOME) option requests that the security policy set the HOME environment variable to the home directory of the target user (root by default) as specified by the password database. Depending on the policy, this may be the default behavior. 

(Starting from Ubuntu 19.10, -H is no longer needed as this is now the default behaviour. See: How does sudo handle $HOME differently since 19.10?)

-u user The -u (user) option causes sudo to run the specified command as a user other than root. To specify a uid instead of a user name, use #uid. When running commands as a uid, many shells require that the '#' be escaped with a backslash ('\'). Security policies may restrict uids to those listed in the password database. The sudoers policy allows uids that are not in the password database as long as the targetpw option is not set. Other security policies may not support this. 

su can only switch user without providing a password if you are root. See Caleb's answer

You can modify the /etc/pam.d/su file to allow su without password. See this answer.

If you modified your auth file to the following, any user that was part of group somegroup could su to otheruser without a password.

auth sufficient pam_rootok.so auth [success=ignore default=1] pam_succeed_if.so user = otheruser auth sufficient pam_succeed_if.so use_uid user ingroup somegroup 
rubo77@local$ su otheruser -c 'echo "hello from $USER"' hello from otheruser 

Источник

Читайте также:  Как добавить скрипты linux
Оцените статью
Adblock
detector