Stop at the root level in the middle of the script that was run using sudo

There is a list of teams that succeed only if preceded by them sudo.
There is another list of commands that are executed only when the user runs them without sudo.

I want to execute all these commands from the same script.
I would like to avoid having to do the following:

#!/usr/bin/env bash
sudo sudo_command_one;
sudo sudo_command_two;
sudo sudo_command_three;
non_sudo_command;
sudo sudo_command_four;

The reason for this is that sudo has a timeout, and these commands are likely to take a lot of time. I don’t want to be burdened with having to re-enter my sudo password. I could extend the sudo timeout indefinitely, but this is also something that I would prefer to avoid if there is an easier way.

Therefore, I am going to run the script as follows:

sudo ./script

non-sudo.
:

#!/usr/bin/env bash
sudo_command_one;
sudo_command_two;
sudo_command_three;
[turn sudo off for a moment]
non_sudo_command;
[ok, turn sudo back on]
sudo_command_four;

, , sudo, , sudo ( ).

+4
2

script, sudo, :

su -c "shell command; shell command" $SUDO_USER 

script , sudo.

, sudo SUDO_USER .

, .

script :

myscript.sh

#!/bin/bash
echo "Part 1"
echo "now running as:"
whoami
echo "SUDO_USER is:"
echo $SUDO_USER
su $SUDO_USER <<EOF
echo "Part 2"
echo "now running as:"
whoami
echo "SUDO_USER is:"
env | grep ^SUDO_USER
sleep 5
EOF
echo "Part 3"
echo "now running as:"
whoami
echo "SUDO_USER is:"
echo $SUDO_USER

sudo ./myscript.sh

Part 1
now running as:
root
SUDO_USER is:
paul
Part 2
now running as:
paul
SUDO_USER is:
SUDO_USER=paul
Part 3
now running as:
root
SUDO_USER is:
paul

: sudo. sudo ,

sudo su

echo $SUDO_USER
---> me

sudo su
echo $SUDO_USER
---> root

SUDO_USER root, . su $SUDO_USER root. , , .

+7

script.

#! /bin/bash

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root";
   exit 1;
else
    NON_ROOT_USER=$(who am i | awk '{print $1}');
    echo "root ran this echo.";
    sudo -u $NON_ROOT_USER echo "$NON_ROOT_USER ran this echo.";
fi

sudo./script.sh

+1

Source: https://habr.com/ru/post/1570541/


All Articles