Search code examples
linuxsecuritysudosudoers

sudo su to an other user to run script


I am trying to login as USER1 and switch user to USER2 and execute some scripts (100+ scripts, can't list them all out in the sudoer file one by one) as USER2

in the Sudoer file i have

   USER1 ALL=(USER2) NOPASSWD: ALL

When i run the following as USER1

  sudo su - USER2 -c "test.sh"

I get

Sorry, user USER1 is not allowed to execute '/bin/su - USER2 -c test.sh' as root

if i run

  sudo su - sassrv

I get

Sorry, user USER1 is not allowed to execute '/bin/su - USER2'

If i change the Sudoer file to

         USER1 ALL=(ALL) NOPASSWD: /bin/su - USER2

It will let me switch user, but i am still getting

Sorry, user USER1 is not allowed to execute '/bin/su - USER2 -c test.sh' as root

How can i achieve this?


Solution

  • You wanted to run test.sh as USER2 with sudo, but instead you run su as root.

    su may in turn try to run test.sh as USER2, but that's beyond the scope and knowledge of sudo. From sudo's point of view, the only thing you're doing is trying to run a command as root.

    Instead, ask sudo to run test.sh as USER2 directly:

    sudo -u USER2 test.sh
    

    PS: sudo su in any context is a code smell that indicates a lack of understanding of what sudo is and does.