Search code examples
linuxshellsshssh-keys

Run a cmd from linux server as a different user


I have 2 service accounts SA1 and SA2. Currently my team has passwords of both accounts, I want to restrict them to have password of only service account (SA1). But team needs to access some logs using SA2 (Please note that logs can be accessed only using SA2). How can i run a script to ssh into the same server but as a different user and get the logs using some cmd and copy it into a common location with 777 permission so that even SA1 can access it.


Solution

  • This is what "sudoers" is for.

    1. Write a script that accesses the files you want and install it so SA2 can run it.
    2. Create a file /etc/sudoers.d/accesslogs:
      Cmnd_Alias ACCESSLOGS = /path/to/myscript.sh
      
      SA1 ALL = (SA2) NOPASSWD: ACCESSLOGS
      
    3. As SA1, run sudo /path/to/myscript.sh and it will work with no password required.

    You can also configure it so that they need to enter the SA1 password to run the script. Naturally, this technique is only as secure as your script, so write it carefully.