Running Docker commands included in a shell script alongside other Linux commands and switching users - shell

Using the Linux terminal, I run bash scripts (.sh files) containing sequences of commands I want to execute.
The issue is that I am unable to run a Docker command from within my shell script. I can run this Docker command when it's typed directly at the terminal with root privileges but not when I include it in the shell script file.
My script executed as a general user from command line, looks like this:
#!/usr/bin/env bash
cd /home/user/docker_backup
# remove /home/user/docker_backup/data
rm -rf data
# Switch to root privileges. my system is set to only run Docker as root
su
# Copy a folder from Docker container to host OS
docker cp <container-name>:/home/user/data /home/user/docker_backup
# More general user commands
cd ..
My code only runs until the su line above. After i enter the root password, nothing happens. if i type exit, i get permission errors, meaning the docker cp command failed.

**
This is my desired solution
**After thorough research, as I wanted to run my script as a general user, and only run certain commands as Root when necessary, I came up with a solution that works.
My script now looks like this (run with
$ sh script_name.sh):
#!/usr/bin/env bash
cd /home/user/docker_backup
# remove /home/user/docker_backup/data
rm -rf data
# Switch to root privileges. my system is set to only run Docker as root
su - root -c "docker cp <container-name>:/home/user/data /home/user/docker_backup"
# More general user commands
cd ..
Run shell script as general user. For commands that require root privileges, I use su - root -c "<command>". Terminal prompts for root password and executes command in quotes as root, then shell proceeds as general user.

Actually posting this as an answer:
You switch your current user to root during the script, but the script was executed by your own user.
So the docker cp command will also be executed as your own user, but you will be logged into the root account.
This results in you not seeing the output of docker cp (which might give you insight to not working - I think insufficient privilege).
A solution to this is either using sudo before docker cp, starting the script as root or adding your user to the group "docker", which authorizes your user to use the docker commands

I had the similar issue where the docker commands were running fine on the Terminal but the same commands were not running when I compiled them into a bash script and the issue was basically because of two reasons.
The docker commands need to be run with uplifted privileges that is with the sudo command ( Eg: sudo docker ps works but docker ps won't work). One could add the current user to docker group so that we need not use sudo with each docker command. Please visit this link and follow the section 2 to do the same.
Run the script in the correct way
One should have #! bin/bash at the starting of the script. It is a shebang that is required by each script.
One should save the file without .sh extension
One should provide the execution permission to the script by giving command chmod 777 script_name
run the script with bash script_name

Related

Unable to remotely execute Shell script with root priviledges

There is a script located in following path
/usr/local/bin/subrun
The Owner & usergroup of above file is root
When I run above script locally using following command in BASH shell:
/bin/sh /usr/local/bin/subrun
It runs perfectly fine
But When I try to run same script remotely using following command in BASH shell:
ssh user#host /usr/local/bin/subrun
It throws an error :
/usr/local/bin/subrun: Command not found.
Question : How do I resolve this ? Does this has to do with 'root' (Owner & Usergroup of script)
PS: Also there is another script in the same location with different Owner & usergroup (for e.g. Owner : manager & Usergroup : admin). This script can be run locally or remotely without any issue
PS2: 'subrun' script file has following levels of permission '-rwxr-xr-x' (And I am not allowed to change permission using chmod. It says Operation not permitted
Since you run it locally as:
/bin/sh /usr/local/bin/subrun
rather than just:
/usr/local/bin/subrun
it's probaby not an executable file on either machine and so you should do the same when trying to run it remotely and use:
ssh user#host '/bin/sh /usr/local/bin/subrun'
instead of
ssh user#host /usr/local/bin/subrun
or make it executable on every machine by running chmod oug+x /usr/local/bin/subrun or similar on every machine and THEN you can call it as just /usr/local/bin/subrun on every machine.

run inline shell script as root

I have a user, who's a passwordless sudoer. I need to execute shell script file with him, and make him execute one block as sudo. E.g:
su root <<"AS_ROOT"
# do something with my linux
AS_ROOT
But nothing works. I tried:
su - root <<...
sudo -s -- <<...
It barks back at me. I'm on ubuntu 16.04 lts.
Thank you.
As Cyrus points out, su is a different utility to which sudo's configuration doesn't apply.
It sounds like you're looking for something like this:
sudo -s <<'AS_ROOT'
echo "Hi from $USER."
AS_ROOT
This should output Hi from root.
Note that -s is needed to tell sudo to create a shell in order to interpret the commands passed via stdin (the here-doc). That shell is the current user's default shell, as reflected in environment variable $SHELL.

Run a command as the standard user, from a sudo elevated script

If a bash script has been executed with sudo, how can a command within the script run as the currently logged in user, instead of root and then revert to root to continue running other commands?
For example: -
#!/usr/bash
touch fileOwnedByRoot.txt
touch fileOwnedByUser.txt
touch otherRootFile.txt
If this script is run with sudo, without changing the order of commands, how can the 2nd touch command be run as the standard user?
The script is only a simple example, so using chmod to change ownership of files created is irrelevant.
The actual script I'm using is being run by an installer, so running with elevated privileges is a requirement, but specific commands must be run as the user running the installer, whose name is not known.
Use su - another_user -c "<command>" to run that specific command:
#!/bin/bash
touch /tmp/f1
su - another_user -c "touch /tmp/f2"
touch /tmp/f3
As commented by chepner below, you need to use $SUDO_USER or $SUDO_UID to get the name of the real user running the sudo command:
su - $SUDO_USER -c "touch /tmp/f2"
This way, the file will be touched by the user running the command.
You can test with:
#!/bin/bash
echo "sudo_user: $SUDO_USER"
echo "sudo_uid: $SUDO_UID"
And run the script either with ./script or sudo ./script. In the second case the values will be populated.
Don't run the script as sudo, just the commands that require elevated privileges.
#!/bin/bash
sudo touch fileOwnedByRoot.txt
touch fileOwnedByUser.txt
sudo touch otherRootFile.txt
According to the man page the environment variable SUDO_USER is set when you run sudo, so you could do something like:
#!/usr/bash
touch fileOwnedByRoot.txt
sudo ${SUDO_USER} touch fileOwnedByUser.txt
touch otherRootFile.txt
I haven't tested this, and don't know if it work differently on OSX, but it's worth a shot.

Bash script - change to root then exit root

If I am in the middle running a bash script, is there any way to switch over to root user, process a command, and then exit root mode? For example, I'd like to include these commands in the middle of a bash script:
sudo su
umount /home/user/myMount
exit
The problem is that after the first line runs, the shell goes into root mode, but then stops execution. Of course, I could create and execute a second script at this point, but this defeats the purpose of scripting since I could just type the commands myself.
The other obvious idea is to run the script from with the root user at the outset. However, some of the other commands in this script fail if I am the root user since they would expose security vulnerabilities with this much access.
So, I need a way to get into the root and then exit out of it.
Thanks.
Specify a Command
The sudo command can take a command and optional arguments. For example:
sudo umount /home/user/myMount
This will run only the specified command and its arguments as root. If you want to run the command as another user, you can use the -u flag. For example, to run umount as Fred, you could use:
sudo -u fred umount /home/user/myMount
While there are certainly other ways to address this issue, this is by far the simplest and most common.
In order to perform the umount as root, use
sudo umount /home/user/myMount

Changing to root user inside shell script

I have a shell script which needs non-root user account to run certain commands and then change the user to root to run the rest of the script. I am using SUSE11.
I have used expect to automate the password prompt. But when I use
spawn su -
and the command gets executed, the prompt comes back with root and the rest of the script does not execute.
Eg.
< non-root commands>
spawn su -
<root commands>
But after su - the prompt returns back with user as root.
How to execute the remaining of the script.
The sudo -S option does not help as it does not run sudo -S ifconfig command which I need to find the IP address of the machine.
I have already gone through these links but could not find a solution:
Change script directory to user's homedir in a shell script
Changing unix user in a shell script
sudo will work here but you need to change your script a little bit:
$ cat 1.sh
id
sudo -s <<EOF
echo Now i am root
id
echo "yes!"
EOF
$ bash 1.sh
uid=1000(igor) gid=1000(igor) groups=1000(igor),29(audio),44(video),124(fuse)
Now i am root
uid=0(root) gid=0(root) groups=0(root)
yes!
You need to run your command in <<EOF block and give the block to sudo.
If you want, you can use su, of course. But you need to run it using expect/pexpect that will enter password for you.
But even in case you could manage to enter the password automatically (or switch it off) this construction would not work:
user-command
su
root-command
In this case root-command will be executed with user, not with root privileges, because it will be executed after su will be finished (su opens a new shell, not changes uid of the current shell). You can use the same trick here of course:
su -c 'sh -s' <<EOF
# list of root commands
EOF
But now you have the same as with sudo.
There is an easy way to do it without a second script. Just put this at the start of your file:
if [ "$(whoami)" != "root" ]
then
sudo su -s "$0"
exit
fi
Then it will automatically run itself as root. Of course, this assumes that you can sudo su without having to provide a password - but that's out of scope of this answer; see one of the other questions about using sudo in shell scripts for how to do that.
Short version: create a block to enclose all commands to be run as root.
For example, I created a script to run a command from a root subdirectory, the segment goes like this:
sudo su - <<EOF
cd rootSubFolder/subfolder
./commandtoRun
EOF
Also, note that if you are changing to "root" user inside a shell script like below one, few Linux utilities like awk for data extraction or defining even a simple shell variable etc will behave weirdly.
To resolve this simply quote the whole document by using <<'EOF' in place of EOF.
sudo -i <<'EOF'
ls
echo "I am root now"
EOF
The easiest way to do that would be to create a least two scripts.
The first one should call the second one with root privileges. So every command you execute in the second script would be executed as root.
For example:
runasroot.sh
sudo su-c'./scriptname.sh'
scriptname.sh
apt-get install mysql-server-5.5
or whatever you need.

Resources