InterLinked
InterLinked

Reputation: 1403

How to run command as another user

I have a shell script that makes a few calls to Asterisk at some point and shows some output. Calling Asterisk is the first thing I have tried that seems not to work. I determined the user I setup to run the script didn't have the permissions to run Asterisk, so I looked at ways to run it as root which would get around that (the only other user on the system).

I tried using su with no luck. For the past two hours, I've been messing with sudo and sudoers and not been able to get it working.

For example, here is some code called in my script, run by the user com:

printf "\n"
calls=`sudo "asterisk -rx 'core show channels'" | grep "active call"`
lastinboundcaller=`cat /var/log/asterisk/lastcaller.txt`
printf '%s\n' "Current Call Count: $calls"
printf '%s\n' "Last Inbound Caller: $lastinboundcaller"

Output:

[sudo] password for com:
sudo: asterisk -rx 'core show channels': command not found
Current Call Count:
Last Inbound Caller: Unknown

There are two problems here,

  1. It's prompting for a password. Why it's prompting for the current user's password rather than the root password, I have no idea, but it shouldn't prompt for any password at all.
  2. The Asterisk command asterisk -rx "command" is still not working — in other words, it's still failing to run the Asterisk shell, though it should have permission.

I tried updating my sudoers file and creating a new file in /etc/sudoers.d titled asterisk as well and putting my command in there.

My latest modification to that file was:

com ALL = (ALL:ALL) NOPASSWD: /usr/sbin/asterisk

Before that, I tried:

com ALL = (root) NOPASSWD: /usr/sbin/asterisk

My understanding is this should allow the user com to execute asterisk as sudo without a password. Clearly, something is not working.

I have followed the answers to numerous similar SO posts, like:

Unfortunately, despite following all the answers I've been able to find on this issue, none have worked for me.

Can anyone point me in the right direction here or suggest an alternative? I already consulted a Linux expert and this seems to be the right approach. This is all super easy to do in Windows and I'm surprised it's all this convoluted in Linux.

Upvotes: 0

Views: 748

Answers (1)

Barmar
Barmar

Reputation: 780889

Don't quote the argument to sudo. It expects the first argument to be the name of the command, so it thinks the whole command line is the program name.

It should be

calls=`sudo asterisk -rx 'core show channels' | grep "active call"`

Why it's prompting for the current user's password rather than the root password, I have no idea, but it shouldn't prompt for any password at all.

That's how sudo works. It prompts for the current user's password, and checks /etc/sudoers to see if they're allowed to run the command. You're thinking of su, which prompts for the root password.

Upvotes: 1

Related Questions