8

This may be a stupid question.

I have a script that I want to be portable between Mac OS X and a Linux box I use. In OS X, a command in the script requires sudo, where on the Linux box, it does not.

Long story short, how does one run one command in a script with sudo, while then removing the elevated privileges for the rest of the script?

I have tried to use

su -

and

su -c

but they both seem to error out. (They say "sorry" and move on, I assume because it is trying to run as root and root does not have a password).

I know there has to be a silly and easy way to do this, what does everyone suggest?

3 Answers 3

7

You can 'revoke' the sudo permission (actually: close the sudo time window early) by doing:

sudo -k

Also, you can configure sudo to only allow elevated permissions on certain commands, or even to impersonate non-root for specific commands. See man sudoers. The examples section makes it exceedingly clear that there is virtually no limit to the configurability of sudo (roles, hosts, commands, allow escaping, allow sudo target users, exceptions to allowed things, password less authorization etc etc).

Hopefully an interesting example in your context:

The user fred can run commands as any user in the DB Runas_Alias (oracle or sybase) without giving a password.

   fred           ALL = (DB) NOPASSWD: ALL

If you can't / don't really want to meddle with /etc/sudoers (visudo!) then I suggest using something like

{
     trap "sudo -k" EXIT INT QUIT TERM
     sudo ls # whatever
}
Sign up to request clarification or add additional context in comments.

1 Comment

this was exactly what i needed. run the command, then run sudo -k. thanks very much.
0

Try sudo su instead of su to change back to a regular user.

2 Comments

when i try "sudo su umount /dev/disk1", i get "su: unknown login: umount". looking through man sudo, i can only conclude it is looking for a user named "umount"?
@rick: Yes, it's looking for a user named umount. su is for changing to a different user (usually root) and can only be run as root, so the argument that it takes is a username. sudo is for running one single command as a different user. In your example, you're saying you want to run the command su umount /dev/disk1 as root, which then says you want to change to the user umount (with an extra ignored argument).
0

Use sudo without su:

#!/bin/bash
whoami  # Runs under your regular account
sudo whoami  # Runs as root
whoami  # Runs under your regular account again

Here's the output when I run it:

$ ./sudotest
gordon
Password:
root
gordon

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.