How to run command as another user - bash

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,
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.
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:
Use sudo without password INSIDE a script
https://unix.stackexchange.com/questions/18877/what-is-the-proper-sudoers-syntax-to-add-a-user
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.

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.

Related

Changing user in bash script

I wanted to create an installation script for my raspberry pi which secures the default installation by configuring/hardening ssh, installing a firewall and fail2ban and finally to get rid off the default user of Raspbian. All other parts work but the final part always shows me an error.
The new user is created and added to the sudo group. After that I want to delete the old user 'pi'. As the script runs with sudo in the user context of 'pi' I thought I could solve this by switching to 'su' but I just get an error that the user couldn't be deleted as it is used by a process:
echo "Enter the new user name? Only lower case letters allowed!"
read user
sudo adduser $user && adduser $user sudo
echo "default user 'pi' will now be deleted"
su -c "deluser -remove-home pi"
If I check with 'users' the user 'pi' is gone but I can still log in with this account. How can I solve this problem inside the script?
I tried the answers I found here: How do I use su to execute the rest of the bash script as that user? and here: https://unix.stackexchange.com/questions/361327/how-to-login-as-different-user-inside-shell-script-and-execute-a-set-of-commands but nothing seem to work. I searched Google but I can't find any solution that works. Is it even possible what I'm trying to?
I usually add set -eux at the beginning of the bash script. This allows to debug and find typos and errors.
Try to switch user inside the script with
sudo -i -u ${user} $(command to delete pi here)
Think i found the cause of the problem. 'set -eux' was a great help:
deluser pi
Removing user `pi' ...
Warning: group `pi' has no more members.
userdel: user pi is currently used by process 445
/usr/sbin/deluser: `/usr/sbin/userdel pi' returned error code 8. Exiting.
I tried ps -fu pi to find the process which causes the trouble: it's /lib/systemd/systemd --user Is there a way to stop this process inside the script?

Running sudo in shell script

I am just creating a little script which changes mac address. Everytime I run it i have to enter sudo password. How to allow script to enter password or skip sudo verification?
OR is there another way to create this script?Maybe use python?
So here is my script:
#!/bin/bash
nmcli radio wifi off
sudo macchanger wlp6s0 -a
nmcli radio wifi on
What you want to do is modify the sudoers file to allow the user running the script access to a specific command without having to enter a password.
See this answer for more information: https://askubuntu.com/questions/334318/sudoers-file-enable-nopasswd-for-user-all-commands
In short, call visudo and add the following entry:
your_user ALL=(ALL) NOPASSWD:/path/to/the/binary/macchanger wlp6s0 -a
Of course, exchange /path/to/the/binary/macchanger with the true path, found by running which macchanger.
Now the user your_user can run that single command with those exact arguments via sudo without password.
Also, as Cyrus pointed out, man is your friend. It's a good idea to always check the manpages first. More often than not you're going to find the answer to your question by reading it and trying some ideas. In this case: man visudo and man sudo.conf.
Instead of playing around with sudo and risking giving full root
access to programs that may act irresponsibly you can set
cap_net_admin on the binary:
sudo setcap cap_net_admin+ep "$(command -v macchanger)"
It's just one-time operation. Now you can remove sudo from your
script and it will work.
Maybe use python?
No, that wouldn't help. Language doesn't matter. It's kernel that
allows or forbids performing certain operations.

Remember root password throughout script using Bash

Background
I have a long bash script which setup a large environment of interconnected software, taking several hours to complete. A few of the tasks it performs need to be run as root, for which I use sudo .... The whole process is then paused until the user notices and types in the root password. I seek some way for the user to type in the root password only at the beginning of the script, and then automatically supply it when required by sudo later.
My thoughts on possible (bad) solutions
I could store the password directly in a variable and then supply it using
echo "${root_password}" | sudo -S ...
but something tells me that this is bad practice.
Another workaround would be to force the user to run the entire script as root, but wouldn't that lead to different permissions for all of the files generated without the use of sudo?
You can prompt it at the start of your script, so it is not plain text hard saved.
Example:
#!/bin/bash
read -s -p "[sudo] sudo password for $(whoami): " pass
echo $pass | sudo -S apt-get update
help read:
-r do not allow backslashes to escape any characters
-s do not echo input coming from a terminal
I suggest you figure out all of the commands you need the script to run using SUDO, ensure the script is run by a special unprivileged user (e.g. scriptuser), and then edit /etc/sudoers to permit scriptuser to run those commands with NOPASSWD
As an example:
scriptuser ALL = NOPASSWD: /bin/kill, /usr/bin/othercommand, etc.
If you know the complete commands, including arguments, that's ideal (it means that an attacker that compromises the scriptuser account can only run those specific commands as root)
Sudo has a lot of options configurable in /etc/sudoers. If you man sudoers , you should see all of them. Forewarning: This man page is very hard to understand. Find examples. Test them. Ask on StackExchange.

osx - sudo with password execute

Was trying to figure out how to execute a sudo command with the password as a parameter.
echo mypassword | sudo -S command
was using this reference Use sudo with password as parameter
However, on OS X it keeps say "sudo: incorrect password attempt" however that passwords is correct.
what am i doing wrong?
As pointed out in the comments already, what you're doing is a very bad idea because it leaves the password of an account laying around. Instead, if you need to run a specific command with sudo from a script, you could -- and you should -- define that single command for one specific user in such a way that its execution is allowed without having to type in the password.
So, you should edit /etc/sudoers to include an entry for your specific user for that one, single, specific command with the tag NOPASSWD:
youruser yourhostname = (root) NOPASSWD: /some/path/your/command
Or if you really don't feel like typing in the hostname of your computer, then go for:
youruser ALL = (root) NOPASSWD: /some/path/your/command
That way you will possibly leak the ability of executing that one, single command as root instead of leaking your password and with it the possibility of running any commands as root.

Running script with admin permissions on OS X

I've tried my best to find out a solution with the many script questions on Stack Overflow and the internet, but I can't seem to find the solution I need.
What I want to do is create a more automated and less clicking solution to remove all the Mobile cached user accounts on a system. I've been logging in and manually going to user accounts and removing the users one at a time by clicking the "-" button, then clicking "Delete Immediately" for the user data. This works, but is time consuming and I have better things to do with my time. So I knew there had to be a way to do this with a script.
I ran across this code:
for cuser in `dscl . -list /Users AuthenticationAuthority | grep LocalCachedUser | awk '{print $1}' | tr '/n' ' '`; do
dscl . -delete /Users/$cuser
done
If I run this in terminal I get permission errors. So I figured I need to run it with sudo. So I started looking into creating AppleScripts to run the script, but I can't seem to find the right way to do it.
Any ideas? By the way, I'm new to scripting on the Mac, so please comment your code so I know whats happening, and so I don't just run some script code without know what it'll do. :)
Thanks
To perform a shell script with sudo or administrator privileges append with administrator privileges to the end of your do shell script line. For example:
do shell script "/path/to/script/file.sh" user name "adminusershortname" password "password" with administrator privileges
You can find more on Apple's technote dealing with do shell script
That said, saving this as a shell script and running the shell script using sudo would work just as well.
#! /bin/sh
for cuser in `/usr/bin/dscl . -list /Users AuthenticationAuthority | grep LocalCachedUser | awk '{print $1}' | tr '/n' ' '`; do
/usr/bin/dscl . -delete /Users/$cuser
done
Save it as say removeUser.sh, use chmod to set it as executable (chmod 755) and then run it (sudo ./removeUser.sh)
You can do this by editing your system's sudoers file. This will allow the account you use to run this script (via cron, etc.) the ability to run sudo without a password.
To edit the sudoers file you use visudo, but it must be run with admin permission. Try:
$ sudo visudo
Add a line like the following to the end of the file, replacing user_name with the user who will run your script. Note, use tabs between each field.
user_name ALL=(ALL) NOPASSWD:ALL
Now user_name should be able to type sudo and will not be prompted for a password.
Also note that visudo is a text editor that mirrors the vi editor and uses the same commands as vi.
I don't have a mac handy so I can't verify if this would work.
Try running
su -
Then running your script. If that works, try
crontab -e
and adding an entry to run that script of yours.
Are you familiar with crontab? well if not google it if need be.
But basically to run it every day at midnight you'd have something like
0 * * * * /path/to/script
See: http://en.wikipedia.org/wiki/Cron

Resources