Execute Script as Another User Whilst Not Being Root

As a root user can I execute commands in BASH as another user without requiring a password?

In the second example, the $USER variable is expanded before su is executed. This can be prevented by quoting EOF.

su other_user <<'EOF'
echo Current user: $USER
EOF

Or you can execute the script to do it in the root shell, also using a here-doc:

su other_user <<END
bash user.sh
END

or you can use the -c option to su:

su other_user -c 'bash user.sh'

Run script as another user on Linux

The answer is change from su to sudo.

su is primarily for switching users, while sudo is for executing commands as other users. The -u flag lets you specify which user to execute the command as:

sudo -u wayne '/home/wayne/script2.sh'

gives Sorry user is not allowed to execute

Running some parts of the script with root and other parts with normal user

You need the non-evaluated user in some variable.

How you want to do this depends on your actual use case.

You can look at:

Nasty temp file:

echo "$USER" >  /tmp/thatsme.tmp
su -
# Hmm, now hope nobody has changed the tmpfile doing the same trick
orguser=$(cat /tmp/thatsme.tmp)
rm /tmp/thatsme.tmp

Keep environment

export orguser="$USER"
su # Not su -
echo "orguser=${orguser}"

Proces ps -ef and look for original user on the same tty you are on. (not recommended)

Call su - -c script additional parameter and change your master script that it pulls the user from $1.

Preventing a non-root user from running a shell script

If you want to allow a user to run a shell script, you have to give them both "execute" and "read" permissions on the file.

If you want to prevent a user from running a shell script, you have to remove the "read" permission. Even if the file is marked as executable, the user can not execute a non-readable script.

There is no way to allow a user to execute but not read a shell script.

Similarly, there is no way to allow a user to read but not to execute a shell script.

How to run script as another user without password?

Call visudo and add this:

user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh

The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh from a user1 shell. Done.



Related Topics



Leave a reply



Submit