Running a command as another non-root user

Hi,

I am trying to run a command within my KSH script as another user due to permission issues, now both users are non root. I have tried the following command and was unsuccessful:

 echo "<password>" | sudo -S -u <username> -k command

Can I use sudo to run a command as a non-root user?

What's the command's entry in the sudoers file?

This would only work if sudo would accept passwords from stdin, which is not the case (for security reasons).

But even if this wold work you shouldn't do it that way, because you write the password for everybody to read who can read the scripts text. Furthermore, if the password would change you'd have to change the script as well.

Better set up a sudo-rule which allows userA to become userB without any password or to run a certain command (your script) as user B (also without any password). Such a rule would look like:

# cat /etc/sudoers
[....]
userA   ALL=(userB) NOPASSWD: /path/to/command *
[...]

Notice that the asterisk is probably necessary, otherwise one could not use any commandline arguments.

I hope this helps.

bakunin

1 Like

Thanks to RudiC who told me i have to correct myself: sudo does indeed read from stdin when called with the -S option. My bad.

It doesn't make that a good idea, though, and what i said still holds, plus: reading passwords from stdin is in itself a bad idea, which is why it isn't done so normally - not by sudo (without the -S ), not by passwd and similar tools.

bakunin

1 Like

Unfortunately, I cannot access /etc/sudoers as the file is owned by root and doesn't have permissions for others to read/edit.

What other option do I have to run a command as USER A as USER B. I do not mind running it with the password in the script if that is what it takes, however, my command didn't work.

In other words you are not root, so can not edit and modify sudoers file, it would have been simpler if you replied at rudiC first post, as you cannot use sudo if your user is not defined with what is enabled in the sudoers file...
There is always ways of bypassing only by doing so you create breaches and possible security breaches, so we will not help you doing so unless we know at what you are up to...
And the only good ( safest that is ) is to see an admin and get some sudo update