Non-interactive bash script re logging after `usermod -aG` - linux

There are commands that require users to be in a group to execute.
I am running a non-interactive bash script script.sh like below
#!/bin/bash
sudo usermod -aG $USER docker
# this line requires user logging to succeed
docker ps
When invoking the script for the first time bash script.sh, the line docker ps will complain insufficient permission since the new group membership modified by line sudo usermod -aG $USER docker requires the user to re-log into the shell to take effect.
My question: is there a way I can trigger the re-log in an non-interactive way?

When you make changes to users like adding, removing groups, you will have to logout from the current session and then, you will be able to use the docker command without any problem.
Another solution if you are working with terminal can use the su command.
For example, your script can be like this:
#!/bin/bash
sudo usermod -aG $USER docker
su - $USER #this line is used to login with the $USER as a login shell
The docker ps command will not work in this script, I forgot to mention that when you run su - $USER you will have to type that command inside that login shell.
But, there is another solution for that, you can use the -c option for su command. For example:
su - $USER -c "docker ps"
Or if you want to use several command you can try using a semicolon at the end of each script:
su - $USER -c "docker ps;docker images;..."
Or if you will have several commands, you can save them inside a file and send the text as parameter of the -c option:
In your text file might be (dockerscripts.txt):
docker ps
docker images
docker info
And the su command might be:
su - $USER -c "$(cat dockerscripts.txt)"
A tip for checking the current groups of a logged user is to use the command groups
So, if you try this:
sudo usermod -aG $USER docker
groups # this will display the current groups of $USER but the `docker` group will not be there yet
su - $USER
After that command you will be in the login shell, so you will have to type the command groups and when you run it, this will display the current groups of $USER including the docker group.
Note: When you logout from the login shell su - $USER the group will not be there again, so If you want to use the docker command you will have to use su - $USER again. The effective way for working with the new group is to log out from the session (if you are working with a desktop environment).
You can check this link fore more useful information: newgrp command in Linux

Related

Docker Permission Denied During Setup

I am attempting to install and use docker for the first time. I have followed the guidelines provided in the answer to this question:
sudo groupadd docker
which at this point returns (as expected):
groupadd: group 'docker' already exists
I then attempt to add the user to the group:
sudo usermod -aG docker $wb_s2s
which only returns
Options:
-b, --badnames allow bad names
-c, --comment COMMENT new value of the GECOS field
-d, --home HOME_DIR new home directory for the user account
-e, --expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE
-f, --inactive INACTIVE set password inactive after expiration
to INACTIVE
-g, --gid GROUP force use GROUP as new primary group
...
I then try to log out and lock back in and/or restart the computer/docker (I've tried everything). But when I run:
docker run hello-world
I get an error:
docker: Got permission denied while trying to connect to the Docker daemon socket at ... connect: permission denied. See 'docker run --help'.
Can anyone tell me where I went wrong?
When you add your user to the group, the docs meant literally $USER to refer to your user wb_s2s (which is a variable presented in your shell's environment for purposes like this)
adding $ will make it a variable the shell interprets as an empty string
% echo $USER
ti7
% echo $ti7
% echo $whatever
You could use the $USER variable, or just remove the $ from your attempt to add your user to the group
-sudo usermod -aG docker $wb_s2s
+sudo usermod -aG docker wb_s2s

docker.sock permission denied

When I try to run simple docker commands like:
$ docker ps -a
I get an error message:
Got permission denied ... /var/run/docker.sock: connect: permission denied
When I check permissions with
$ ls -al /var/run/
I see this line:
srw-rw---- root docker docker.sock
So, I follow an advice from many forums and add local user to docker group:
$ sudo usermod -aG docker $USER
But it does not help. I still get the very same error message. How can I fix it?
For those new to the shell, the command:
$ sudo usermod -aG docker $USER
needs to have $USER defined in your shell. This is often there by default, but you may need to set the value to your login id in some shells.
Changing the groups of a user does not change existing logins, terminals, and shells that a user has open. To avoid performing a login again, you can simply run:
$ newgrp docker
to get access to that group in your current shell.
Once you have done this, the user effectively has root access on the server, so only do this for users that are trusted with unrestricted sudo access.
Reason: The error message means that the current user can’t access the docker engine, because the user hasn't enough permissions to access the UNIX socket to communicate with the engine.
Quick Fix:
Run the command as root using sudo.
sudo docker ps
Change the permissions of /var/run/docker.sock for the current user.
sudo chown $USER /var/run/docker.sock
Caution: Running sudo chmod 777 /var/run/docker.sock will solve your problem but it will open the docker socket for everyone which is a security vulnerability as pointed out by #AaylaSecura. Hence it shouldn't be used, except for testing purposes on the local system.
Permanent Solution:
Add the current user to the docker group.
sudo usermod -a -G docker $USER
Note: You have to log out and log in again for the changes to take effect.
Refer to this blog to know more about managing Docker as a non-root user.
Make sure your $USER variable is set
$ echo $USER
$ sudo usermod -aG docker $USER
logout
Upon login, restart the docker service
$ sudo systemctl restart docker
$ docker ps
enter the command and explore docker without sudo command
sudo chmod 666 /var/run/docker.sock
As mentioned earlier in the comment the changes won't apply until your re-login. If you were doing a SSH and opening a new terminal, it would have worked in new terminal
But since you were using GUI and opening the new terminal the changes were not applied. That is the reason the error didn't go away
So below command did do its job, its just a re-login was missed
sudo usermod -aG docker $USER
You need to manage docker as a non-root user.
To create the docker group and add your user:
Create the docker group.
$ sudo groupadd docker
Add your user to the docker group.
$ sudo usermod -aG docker $USER
Log out and log back in so that your group membership is re-evaluated.
If testing on a virtual machine, it may be necessary to restart the virtual machine for changes to take effect.
On a desktop Linux environment such as X Windows, log out of your session completely and then log back in.
On Linux, you can also run the following command to activate the changes to groups:
$ newgrp docker
Verify that you can run docker commands without sudo.
$ docker run hello-world
As my user is and AD user, I have to add the AD user to the local group by manually editing /etc/group file. Unforrtunately the adduser commands do not seem to be nsswitch aware and do not recognize a user not locally defined when adding someone to a group.
Then reboot or refresh /etc/group. Now, you can use docker without sudo.
Regards.
***Important Note on these answers: the docker group is not always "docker" sometimes it is "dockerroot", for example the case of Centos 7 installation by
sudo yum install -y docker
The first thing you should do, after installing Docker, is
sudo tail /etc/group
it should say something like
......
sshd:x:74:
postdrop:x:90:
postfix:x:89:
yourusername:x:1000:yourusername
cgred:x:996:
dockerroot:x:995:
In this case, it is "dockerroot" not "docker". So,
sudo usermod -aG dockerroot yourusername
logout
When I try to run simple docker commands like: $ docker ps -a
I get an error message: Got permission denied ... /var/run/docker.sock: connect: permission denied.
[…] How can I fix it?
TL;DR: There are two ways (the first one, also mentioned in the question itself, was extensively addressed by other answers, but comes with security concerns; so I'll elaborate on this issue, and develop the second solution that can also be applicable for this fairly sensible use case).
Just to recall the context, the Docker daemon socket is owned by root:docker:
$ ls -l /var/run/docker.sock
srw-rw---- 1 root docker 0 janv. 28 14:23 /var/run/docker.sock
so with this default setup, one needs to prepend all docker CLI commands by sudo.
To avoid this, one can either:
add one's user account ($USER) to the docker group − but that's quite risky to do this on one's personal workstation, as this would amount to provide all programs run by the user with root permissions without any sudo password prompt nor auditing.
See also:
this page in the official Docker documentation:
https://docs.docker.com/engine/security/#docker-daemon-attack-surface
this page that documents the related exploit:
https://fosterelli.co/privilege-escalation-via-docker.html
one can otherwise prepend sudo automatically without typing sudo docker manually: to this aim, a solution consists in adding the following alias in the ~/.bashrc (see e.g. this thread for details):
__docker() {
if [[ "${BASH_SOURCE[*]}" =~ "bash-completion" ]]; then
docker "$#"
else
sudo docker "$#"
fi
}
alias docker=__docker
Then one can test this by opening a new terminal and typing:
docker run --pul〈TAB〉 # → docker run --pull
# autocompletion works
docker run --pull always --rm -it debian:11 # ask one's password
\docker run --help # bypass the alias (thanks to the \) and ask no password
With the help of the below command I was able to execute the docker command without sudo
sudo setfacl -m user:$USER:rw /var/run/docker.sock
bash into container as root user
docker exec -it --user root <dc5> bash
create docker group if it's not already created
groupadd -g 999 docker
add user to docker group
usermod -aG docker jenkins
change permissions
chmod 777 /var/run/docker.sock
You have to use pns executer instead of docker.
run the following patch which modifies the configmap and you are all set.
kubectl -n argo patch cm workflow-controller-configmap -p '{"data": {"containerRuntimeExecutor": "pns"}}' ;
ref: https://www.youtube.com/watch?v=XySJb-WmL3Q&list=PLGHfqDpnXFXLHfeapfvtt9URtUF1geuBo&index=2&t=3996s

How to grant Nagios permissions to run some commands in custom script?

I have been making some custom shell scripts for my nagios machine. I was able to make them run just fine but for some reason some commands in the script don't seem to be working.
For instance commands like echo, cut , ps , grep work fine but commands like touch, useradd dont seem to work, even with sudo. If I run the script from the terminal, all the commands in the script work.
How can I give nagios permissions to run these commands?
I'm running nagios3 on ubuntu 14.04.5 lts
Edit: Added a few lines of code which aren't being run
sudo useradd -m $USERNAME
(echo $PASSWORD; echo $PASSWORD) | sudo smbpasswd -s -a $USERNAME
Standard way is setup permission for Nagios user on monitored server, for instance NRPE, in /etc/sudoers file.
1. method
Try add something like this in your sudoers file.
Defaults:nrpe !requiretty
nrpe ALL= NOPASSWD: useradd -m
nrpe ALL= NOPASSWD: smbpasswd -s -a
PS: For easy editing sudoers file you can use visudo command ;-)
2. method
Or you can try add Nagios user to sudo group via sudo usermod -aG sudo <username>
-a stands for add
G is for group
Tell nagios to run the script as sudo in your .cfg file...
Assuming its permissions problem.
Edit /etc/sudoers file using visudo, this allows automatic file check for errors.
Defaults:nrpe !requiretty
nrpe ALL=(root) NOPASSWD: /path/to/your/command/or/script
Verify sudo has assigned the above permissions to the user in this case nrpe
sudo -U nrpe -l
you should see the command you added listed within the outpul
Edit /etc/nagios/nrpe.cfg
Add your command to the end of the file
e.g.
command[your_command]=/usr/bin/sudo /path/to/your/command/or/script
Restart nrpe
Centos: systemctl restart nrpe (use the command available based on your Operating system)

Run script as another user on Linux

I am trying to create a Linux terminal menu by way of a simple script. Within the script it will have some commands that will submit a job (a shell script for example) as another user without password prompt.
I was able to find the following post and this worked. how to run script as another user without password
However, there was one side affect. It appears the user can run other scripts in that users folder which I don't want.
Any suggestions/help welcome.
For the sake of this. Here is what I have:
Username temp1, which is the user that will be running the menu.
uid=1001(temp1), gid=1001(temp1), groups=1001(temp1)
Username wayne, which is the user that the script must be submitted as to run the job
uid=1000(wayne), gid=1000(wayne),groups=1000(wayne),4(adm),24(cdrom),27(sudo),30(dip)...
Script script1.sh, script2.sh owned by wayne.
-rwxr-xr-x script1.sh
-rwxr-xr-x script2.sh
If I try to go to /home/wayne as temp1 user I get permission denied (expected)
I set the scripts to chmod 700 for wayne. So technically no one can run them other than wayne.
I have edited sudo file and have the following entry:
temp1 ALL(wayne) NOPASSWD: /home/wayne/script1.sh
When I run command su -c "/home/wayne/script1.sh" -s /bin/sh wayne the script runs (as expected)
When I run command su -c "/home/wayne/script2.sh" -s /bin/sh wayne the script runs (not expected).
Any ideas?
The answer is change from su to sudo.
su is primarily for switching users, while sudo is for executing commands as other users. The -u flag lets you specify which user to execute the command as:
sudo -u wayne '/home/wayne/script2.sh'
gives Sorry user is not allowed to execute
Solution: In order to run commands/scripts as another user on linux/unix you need sudo permission and run the following formula:
sudo -H -u <user> bash -c '<some-command>'
For example:
sudo -H -u wayne bash -c 'echo "user:$USER|home:$HOME|action:run_script"; ./home/wayne/script.sh'
from Documentation:
sudo allows a permitted user to execute a command as the superuser or
another user, as specified by the security policy.
-H The -H (HOME) option requests that the security policy set
the HOME environment variable to the home directory of the
target user (root by default) as specified by the password
database. Depending on the policy, this may be the default
behavior.
-u user The -u (user) option causes sudo to run the specified
command as a user other than root. To specify a uid
instead of a user name, use #uid. When running commands as
a uid, many shells require that the '#' be escaped with a
backslash ('\'). Security policies may restrict uids to
those listed in the password database. The sudoers policy
allows uids that are not in the password database as long
as the targetpw option is not set. Other security policies
may not support this.

shell scripting that uses sudo su - team and perform rest command under this sudo access only

#!/bin/bash
sudo su - team //// this will change user to team
<somecommnand>
here i have some command like sqlplus that run under this privilege only .
but ,this script first asked for password then i give password but it not run rest of command like .
How to write script that use sudo su and run all command in script below it.
You have several options.
You can just move the sudo command outside of your script, and have people call it like this:
sudo -u team /path/to/your/script
You can put the sudo command in one script and the actual commands you want to run with elevated privileges in another script. That is, people run your_script, which looks like:
#!/bin/sh
sudo -u team /path/to/your_script.real
And your_script.real contains the commands that you want to run with elevated privileges.
If you really want everything in the same script and you don't mind being a little too clever, you can have the script check re-execute itself using sudo like this:
#!/bin/sh
TEAM_UID=500 # replace with correct uid
if [ "$UID" != $TEAM_UID ]; then
exec sudo -u team $0
fi
And you can also feed commands to a shell from stdin, like this:
#!/bin/sh
sudo su - team <<'EOF'
echo my uid is $UID
EOF
You could try having all of the commands on the same line and seperate them with ';'.
eg. 'sudo su; somecommand; another command'
Could also run that script as the intended user.

Resources