How to check if user has sudo privileges inside the bash script? - linux

I would like to check if the user has sudo privileges. This is an approximate example of what I am trying to do. I am trying to get this to work across the following os: centos, ubuntu, arch.
if userIsSudo; then
chsh -s $(which zsh)
fi

Try with this:
$ sudo -v &> /dev/null && echo "Sudoer" || echo "Not sudoer"
Also, IDK how secure will be searching for his membership in the sudo group, i.e:
$ groups "$(id -un)" \
| grep -q ' sudo ' \
&& echo In sudo group \
|| echo Not in sudo group
Or:
$ getent group sudo \
| grep -qE "(:|,)$(id -un)(,|$)" \
&& echo in sudo group \
|| echo not in sudo group

sudo -l will display the commands that the user can run with sudo privileges. If there are no commands that can be run, sudo -l will return an error code and so you could try:
sudo -l && chsh -s $(which zsh)

Usually when you run an script you want to know if end it well or you got an error or what kind of error you got if there was any.
This is a more elaborated snippet, sudoer-script.sh:
## Define error code
E_NOTROOT=87 # Non-root exit error.
## check if is sudoer
if ! $(sudo -l &> /dev/null); then
echo 'Error: root privileges are needed to run this script'
exit $E_NOTROOT
fi
## do something else you
## means it was successfully executed
exit 0
Now you can reuse your script, pipe it or concatenate with other commands
sudoer-script.sh && ls
## in a script
if $(sudoer-script.sh); then
echo 'success'
fi
## capture error
stderr=$(./sudoer-script.sh 2>&1 >/dev/null)
echo $stderr
As a function:
is_sudoer() {
## Define error code
E_NOTROOT=87 # Non-root exit error.
## check if is sudoer
if ! $(sudo -l &> /dev/null); then
echo 'Error: root privileges are needed to run this script'
return $E_NOTROOT
fi
return 0
}
if is_sudoer; then
echo "Sudoer"
else
echo "Not sudoer"
fi

Related

assign output of command to variable in bash script run by root cron

I have been trying to write a script that will backup my minecraft server but only run if I am not actively on the server. The way i am trying to do this is by parsing the output of top and grepping the process name and getting the CPU usage. When I am not on the server the usage is usually less than 10. The server is run as a service so in order to bring it down before the backup and to bring it back up I need to use systemctl stop and systemctl start in so it need to be run as root. This is the script I have:
#!/bin/bash
PATH="$PATH:/usr/bin:/bin"
CPU=`/usr/bin/top -b n1 | /usr/bin/grep bedrock_server | /usr/bin/awk '{ print $9 }' | /usr/bin/cut -d . -f 1`
DATE=`date '+\%m-\%d'`
dirname="/home/brandon/bedrock-backups/$DATE"
if [ "$CPU" -lt 20 ];
then
systemctl stop bedrock-server.service && \
mkdir -p $dirname && chown brandon $dirname && chmod 777 $dirname && \
cd /home/brandon && \
tar -czf $dirname/bedrock-backup.tar bedrock/ && \
chown brandon $dirname/bedrock-backup.tar && chmod 777 $dirname/bedrock-backup.tar && \
echo "Backup Completed Successfully" && \
systemctl start bedrock-server.service
else
echo "Backup terminated due to server activity" && \
exit
fi
The issue seems to be that the output of the top command and all the subsequent parsing does not get assigned to CPU so the script errors out at if [ "$CPU" -lt 20 ] with the error integer expression expected. I tried to run the script in cron's env by adding the line env > ~/cronenv to root's crontab and have it run once then use env - `cat ~/cronenv` /bin/sh to get into crons environment. I run
CPU=`top -b n1 | grep bedrock_server | awk '{ print $9 }' | cut -d . -f 1`
and it works. I tried again as a cron job and I get the same error. Then I read that full paths to commands should be used inside cron so I added /usr/bin to the commands as seen above.
I've tried using #!/bin/sh as well as #!/bin/bash for the shebang. The crontab entry is as follows :
# m h dom mon dow command
SHELL=/bin/bash
PATH="$PATH:/usr/bin:/bin"
27 22 * * * /bin/bash /home/brandon/bin/scripts/backup-bedrock
#* * * * * env > ~/cronenv
I can even run the full script in the cronenv but not scheduled as a cron job.
I do not know what else to try or what I am doing wrong, hoping someone can help me.
Thanks!
Also this is on Ubuntu 20.04 if that matters

How to make a script run commands as root

I'm new to Ubuntu and bash scripts, but I just made runUpdates.sh and added this to my .profile to run it:
if [ -f "$HOME/bin/runUpdates.sh" ]; then
. "$HOME/bin/runUpdates.sh"
fi
The problem I'm having is, I want the script to run as if root is running it (because I don't want to type my sudo password)
I found a few places that I should be able to do sudo chown root.root <my script> and sudo chmod 4755 <my script> and when I run it, it should run as root. But it's not...
The script looks good to me. What am I missing? -rwxr-xr-x 1 root root 851 Mar 23 21:14 runUpdates.sh*
Can you please help me run the commands in this script as root? I don't really want to change the sudors file, I really just want to run the commands in this script at root (if possible).
#!/bin/sh
echo "user is ${USER}"
#check for updates
update=`cat /var/lib/update-notifier/updates-available | head -c 2 | tail -c 1`;
if [ "$update" = "0" ]; then
echo -e "No updates found.\n";
else
read -p "Do you wish to install updates? [yN] " yn
if [ "$yn" != "y" ] && [ "$yn" != "Y" ]; then
echo -e 'No\n';
else
echo "Please wait...";
echo `sudo apt-get update`;
echo `sudo apt-get upgrade`;
echo `sudo apt-get dist-upgrade`;
echo -e "Done!\n";
fi
fi
#check for restart
restartFile=`/usr/lib/update-notifier/update-motd-reboot-required`;
if [ ! -z "$restartFile" ]; then
echo "$restartFile";
read -p "Do you wish to REBOOT? [yN] " yn
if [ "$yn" != "y" ] && [ "$yn" != "Y" ]; then
echo -e 'No\n';
else
echo `sudo shutdown -r now`;
fi
fi
I added the user is to debug, it always outputs my user not root, and prompts for the sudo password (since I'm calling the commands with sudo) or tells me are you root? (if I remove sudo)
Also, is there a way to output the update commands stdout in real time, not just one block when they finish?
(I also tried with the shebang as #!/bin/bash)
setuid does not work on shell scripts for security reasons. If you want to run a script as root without a password, you can edit /etc/sudoers to allow it to be run with sudo without a password.
To "update in real time", you would run the command directly instead of using echo.
Its not safe to do, you should probably use sudoers but if you really need/want to, you can do it with something like this:
echo <root password> | sudo -S echo -n 2>/dev/random 1>/dev/random
sudo <command>
This works because sudo doesn't require a password for a brief window after successfully being used.
SUID root scripts were phased out many years ago if you really want to run scripts as root you need to wrap them in an executable, you can see an example on how to do this on my blog:
http://scriptsandoneliners.blogspot.com/2015/01/sanitizing-dangerous-yet-useful-commands.html
The example is how to change executable permissions and place a filter around other executables using a shell script but the concept of wrapping a shell script works for SUID as well, the resulting executable file from the shell script can be made SUID.
https://help.ubuntu.com/community/Sudoers

unable to execute shell script as a user

I've created one script for environment setup. I need Oracle to be installed as part of the script. below is the script i've written (pardon for errors, i'm new). The problem is, when i executed it, they are running fine individually, but collectively, the script is exiting and failing after "UNZIP" command. Can someone please help?
sudo -i -u oracle mkdir /home/oracle/dump
sudo -i -u oracle cd /home/oracle/dump
JAR1="p13390677_112040_Linux-x86-64_1of7.zip"
JAR2="p13390677_112040_Linux-x86-64_2of7.zip"
folder="/home/oracle/database"
if test -s "$JAR1"
then
echo "$JAR1 exists"
else
sudo -i -u oracle
wget XXXp://XXXXXX/XXXXXX/download/database/11.2.0.4/p13390677_112040_Linux-x86-64_1of7.zip
fi
if test -s "$JAR2"
then
echo "$JAR2 exists"
else
sudo -i -u oracle
wget XXXp://XXXXXXX/software/download/database/11.2.0.4/p13390677_112040_Linux-x86-64_2of7.zip
fi
if test -s "$folder"
then
echo "$folder exists"
else
unzip /home/oracle/p13390677_112040_Linux-x86-64_1of7.zip
unzip /home/oracle/p13390677_112040_Linux-x86-64_2of7.zip
fi
sudo -i -u oracle ORACLE_HOSTNAME=`hostname`
sudo -i -u oracle ./runInstaller $ORACLE_HOSTNAME -silent -responseFile /home/oracle/db.rsp
cd /opt/db/oraInventory
./orainstRoot.sh
cd /opt/db/oracle/11.2.0
./root.sh

shell script ssh command not working

I have a small list of servers, and I am trying to add a user on each of these servers. I can ssh individually to each server and run the command.
sudo /usr/sbin/useradd -c "Arun" -d /home/amurug -e 2014-12-12 -g users -u 1470 amurug
I wrote a script to loop through the list and run this command but I get some errors.
#!/bin/bash
read -p "Enter server list: " file
if [[ $file == *linux* ]]; then
for i in `cat $file`
do
echo "creating amurug on" $i
ssh $i sudo /usr/sbin/useradd -c "Arun" -d /home/amurug -e 2014-12-12 -g users -u 1470 amurug
echo "==============================================="
sleep 5
done
fi
When I run the script it does not execute the command.
creating amurug on svr102
Usage: useradd [options] LOGIN
Options:
What is wrong with my ssh crommand in my script?
Try this script:
#!/bin/bash
read -p "Enter server list: " file
if [[ "$file" == *linux* ]]; then
while read -r server
do
echo "creating amurug on" "$server"
ssh -t -t "$server" "sudo /usr/sbin/useradd -c Arun -d /home/amurug \
-e 2014-12-12 -g users -u 1470 amurug"
echo "==============================================="
sleep 5
done < "$file"
fi
As per man bash:
-t
Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.

Linux shell script hybrid graphic card

Im new to linux scripts. I need to make a script to run the following comands
sudo su
chown -R marko:marko /sys/kernel/debug;
chown marko:marko /sys/kernel/debug/vgaswitcheroo/switch;
exit;
echo ON > /sys/kernel/debug/vgaswitcheroo/switch;
echo IGD > /sys/kernel/debug/vgaswitcheroo/switch;
echo DIS > /sys/kernel/debug/vgaswitcheroo/switch;
echo OFF > /sys/kernel/debug/vgaswitcheroo/switch;
where marko is the username of the current logged user in the system.
Thanks
I think it's better not to alter file permissions in /sys filesystem, you should write your script in a file, say switcheroo.sh, like this:
#!/bin/sh
#If not running under sudo, force sudo
[ $UID -ne 0 ] && exec sudo "$0" "$#"
echo ON > /sys/kernel/debug/vgaswitcheroo/switch
echo IGD > /sys/kernel/debug/vgaswitcheroo/switch
echo DIS > /sys/kernel/debug/vgaswitcheroo/switch
echo OFF > /sys/kernel/debug/vgaswitcheroo/switch
and then execute it using sudo ./switcheroo.sh.
You must make the script executable with the command chmod +x switcheroo.sh.

Resources