How to Run Commands as Another User

In a previous post, we explained how to use “su” to execute a command as another user, but that is only one of the many ways you can accomplish this on a Linux or Unix server. The following techniques each have their own advantages and can help you run programs under different user identifications.

  1. runuser – With this tool, you can substitute user and group IDs. To run a command as a different user type:

    runuser -l username -c 'command'

    “l” designates the user and “c” designates the command. You can also use “g” to specify a group and “m” to preserve environment variables.

  2. sudo – Some operating systems prefer sudo for root authentication and escalation of privileges rather than “su”. If yours does, it may be easier to use it instead of su . It will authenticate against your own password rather than the password used by the target user, which is extremely helpful if you do not know the user’s password.

    To execute a command with sudo using a different user, type:

    sudo -u username -i command

Running a command as a different user can be helpful for system administrators who need to preserve user permissions for another user but also accomplish tasks for them on their VPS or shared hosting accounts. It is particularly useful when helping them with support requests.

 











Comments: