Run bash script with sudo but create files with user as owner - bash

I have a bash script, create-file.sh, that creates a file named a:
$ cat create-file.sh
# /bin/bash
touch a
When I run the script it creates a file 'a' with my user as owner.
$ ./create-file.sh
$ ls -l
-rw-r--r-- 1 shai wheel 0 Aug 16 17:19 a
However when I run the script under sudo the file is created with root as user:
$ sudo ./create-file.sh
$ ls -l
-rw-r--r-- 1 root wheel 0 Aug 16 17:19 a
Is there a way to tell a script that runs under sudo to create the file with my user as owner?
you would be correct to say that a script that touches a single file does not need to run under sudo. This example is of course a reduction of the original problem, my script has much more and does need to run under sudo, but I still want the files to be created with my user as owner.

sudo exports the original username as SUDO_USER; you can chown to that.
#!/bin/bash
touch a
[[ $SUDO_USER ]] && chown "$SUDO_USER" a
Similarly, if your sudo configuration allows (as is default) root to drop privileges to any other user without an explicit password prompt, you can take advantage of that:
#!/bin/bash
# drop privileges back to non-root user if we got here with sudo
depriv() {
if [[ $SUDO_USER ]]; then
sudo -u "$SUDO_USER" -- "$#"
else
"$#"
fi
}
depriv touch a

Related

Unable to switch to root user after ssh into the instance using shell script

I have a scenario to automate the manual build update process via shell script on multiple VM nodes.
For the same, I am trying the below sample script to first ssh into the instance and then switch to root user to perform the further steps like copying the build to archives directory under /var and then proceed with the later steps.
Below is the sample script,
#!/bin/sh
publicKey='/path/to/publickey'
buildVersion='deb9.deb build'
buildPathToStore='/var/cache/apt/archives/'
pathToHomedir='/home'
script="whoami && pwd && ls -la && whoami && mv ${buildVersion} ${buildPathToStore} && find ${buildPathToStore} | grep deb9"
for var in "$#"
do
copyBuildPath="${publicKey} ${buildVersion} ${var}:/home/admin/"
echo "copy build ==>" ${copyBuildPath}
scp -r -i ${copyBuildPath}
ssh -i $publicKey -t $var "sudo su - & ${script}; " # This shall execute all commands as root
done
So the CLI stats for the above script are something like this
admin //this is the user check
/home/admin
total 48
drwxr-xr-x 6 admin admin 4096 Dec 6 00:28 .
drwxr-xr-x 6 root root 4096 Nov 17 14:07 ..
drwxr-xr-x 3 admin admin 4096 Nov 17 14:00 .ansible
drwx------ 2 admin admin 4096 Nov 23 18:26 .appdata
-rw------- 1 admin admin 5002 Dec 6 17:47 .bash_history
-rw-r--r-- 1 admin admin 220 May 16 2017 .bash_logout
-rw-r--r-- 1 admin admin 3506 Jun 14 2019 .bashrc
-rw-r--r-- 1 admin admin 675 May 16 2017 .profile
drwx------ 4 admin admin 4096 Nov 23 18:26 .registry
drwx------ 2 admin admin 4096 Jun 21 2019 .ssh
-rw-r--r-- 1 admin admin 0 Dec 6 19:42 testFile.txt
-rw------- 1 admin admin 2236 Jun 21 2019 .viminfo
admin
If I use sudo su -c and remove &
like:
ssh -i $publicKey -t $var "sudo su -c ${script}; "
Then for once whoami returns the user as root but the working directory still prints as /home/admin instead of /root
And the next set of commands are still accounted for admin user rather than the root. So the admin user do not have the privileges to move the build to archive directory and install the build.
Using & I want to ensure that the further steps are being done in the background.
Not sure how to proceed ahead with this. Good suggestions are most welcome right now :)
"sudo su - & ${script}; "
expands to:
sudo su - & whoami && pwd && ...
First sudo su - is run in the background. Then the command chain is executed.
sudo su -c ${script};
expands to:
sudo su -c whoami && pwd && ...
So first sudo su - whoami is executed, which runs whoami as root. Then if this command is successful, then pwd is executed. As normal user.
It is utterly hard to correctly pass commands to execute on remote site using ssh. It is increasingly hard to do it with sudo su - the command will be triple (or twice?) word splitted - one time by ssh, then by the shell, then by the shell run by sudo su.
If you do not need interactive communication, it's best to use a here document with -s shell option, something along (untested):
# DO NOT store commands to use in a variable.
# or if you do and you know what you are doing, properly quote it (printf "%q ") and run it via eval
script() {
set -euo pipefail
whoami
pwd
ls -la
whoami
mv "$buildVersion" "$buildPathToStore"
find "$buildPathToStore" | grep deb9
}
ssh ... "sudo bash -s" <<EOF
echo "Yay! anything here!"
echo "Note that here document delimiter is not quoted!"
$(
# safely import context to work with
# note how command substitution is executed on host side
declare -f script
# pass variables too!
declare -p buildVersion buildPathToStore buildPathToStore
)
script
EOF
When you use su alone it keeps you in your actual directory, if you use su - it simulates the root login.
You should write : su - root -c ${script};

sudo without password is not giving any output

all "myscript.sh" does right now is echo "hello".
[jack#server1 scripts]$ ./myscript.sh
hello
the root user gave me the option to run the script as root without a password but when I do, the script doesn't print the "hello"
[jack#server1 scripts]$ sudo ./myscript.sh
Password:
[jack#server1 scripts]$
what am I doing wrong here? do I need to add some kind of switch ?
I don't see anything about this in man sudo
by the way, obviously I don't have root access to configure anything about this
this is the content of the script:
#!/bin/bash +xv
echo "hello"
and about the permissions and ownership:
[jack#server1 scripts]$ls -l myscript.sh
-rwxrwxr-x 1 jack SiteAdmin 1279 Dec 4 07:54 myscript.sh

chown directory in bash

I am trying to chown a home directory test for an bash script. I need this functionality because of syncthing which is not syncing the ownerships.
#!/bin/bash
user=test
"chown $user:$user /home/$user"
When I use the above script, I get a message "test.sh: line 5: chown test:test ~/home/test/: No such file or directory
"
Output of
ls -l /home/ |grep test
drwx------ 5 pwresettest 1005 121 2. Nov 04:23 pwresettest
drwx------ 14 test 1001 4096 29. Okt 05:41 test
When I am using the command on the commandline, it works without problems.
Did I do something wrong?
The shell treats the quoted string as a single word to as the name of the command, rather than a command name followed by arguments. Simply take off the quotes you've added in your script:
#!/bin/bash
user=test
chown $user:$user /home/$user
When you use chown on the command line you aren't quoting the entire command. Don't do that in the script either. – Etan Reisner

File permissions, root bash script, edit by user

I have a script that needs to be ran as root. In this script I create directories and files. The files and directories cannot be modified by the user who ran the script (unless there root of course).
I have tried several solutions found here and other sites, first I tried to mkdir -m 777 the directories as so:
#!/bin/bash
...
#Check execution location
CDIR=$(pwd)
#File setup
DATE=$(date +"%m-%d_%H:%M:%S")
LFIL="$CDIR/android-tools/logcat/logcat_$DATE.txt"
BFIL="$CDIR/android-tools/backup/backup_$DATE"
mkdir -m 777 -p "$CDIR/android-tools/logcat/"
mkdir -m 777 -p "$CDIR/android-tools/backup/"
...
I have also tried touching every created file and directory with the $USER as root, like so:
#!/bin/bash
...
#Check execution location
CDIR=$(pwd)
#File setup
DATE=$(date +"%m-%d_%H:%M:%S")
LFIL="$CDIR/android-tools/logcat/logcat_$DATE.txt"
BFIL="$CDIR/android-tools/backup/backup_$DATE"
mkdir -p "$CDIR/android-tools/logcat/"
mkdir -p "$CDIR/android-tools/backup/"
sudo -u $USER touch "$CDIR/"
sudo -u $USER touch "$CDIR/android-tools/"
sudo -u $USER touch "$CDIR/android-tools/logcat/"
sudo -u $USER touch "$CDIR/android-tools/backup/"
sudo -u $USER touch "$CDIR/android-tools/logcat/logcat_*.txt"
sudo -u $USER touch "$CDIR/android-tools/logcat/Backup_*"
...
I have also tried manually running sudo chmod 777 /android-tools/*, and sudo chmod 777 /* from the script directory, gave no errors, but I still cannot delete the files without root permission.
Heres the full script, It's not done yet. Don't run it with an android device connected to your computer.
http://pastebin.com/F20rLJQ4
touch doesn't change ownership. I think you want chown.
If you're using sudo to run your script, $USER is root, but $SUDO_USER is the user who ran sudo, so you can use that.
If you're not using sudo, you can't trust $USER to be anything in particular. The caller can set it to anything (like "root cat /etc/shadow", which would make your above script do surprising things you didn't want it to do because you said $USER instead of "$USER").
If you're running this script using setuid, you need something safer, like id -u, to get the calling process's legitimate UID regardless of what arbitrary string happens to be in $USER.
If you cover both possibilities by making makestuff.sh like this:
# $SUDO_USER if set, otherwise the current user
caller="${SUDO_USER:-$(id -u)}"
mkdir -p foo/bar/baz
chown -R "$caller" foo
Then you can use it this way:
sudo chown root makestuff.sh
sudo chmod 755 makestuff.sh
# User runs it with sudo
sudo ./makestuff.sh
# User can remove the files
rm -r foo
Or this way (if you want to use setuid so regular users can run the script without having sudo access -- which you probably don't, because you're not being careful enough for that):
sudo chown root makestuff.sh
sudo chmod 4755 makestuff.sh # Danger! I told you not to do this.
# User runs it without sudo
./makestuff.sh
# User can remove the files
rm -r foo

Why can't I echo contents into a new file as sudo? [duplicate]

This question already has answers here:
Bash Deployment Script Permission Problem
(2 answers)
Closed 8 years ago.
I came across this weird problem just now and I can't seem to get to the bottom of it. I'm trying to add a config file to /etc/sudoers.d/ but get permission denied. In the example below, the file "tweedle" doesn't exist and:
drwxr-xr-x 2 root root 4.0K Jan 2 18:27 sudoers.d/
So here's the command:
$ sudo echo "tweedle ALL=(ALL) ALL" > /etc/sudoers.d/tweedle
-bash: /etc/sudoers.d/tweedle: Permission denied
It doesn't even work when I break it into two commands:
$ sudo touch /etc/sudoers.d/tweedle
$ sudo echo "poodle" > /etc/sudoers.d/tweedle
When I tested it locally, same problem:
$ cd ~
$ mkdir -m 755 tweedle
$ sudo chown root:root tweedle
$ sudo echo "battle" > ~/tweedle/beetle
-bash: /home/spanky/tweedle/beetle: Permission denied
$ sudo touch tweedle/beetle
$ sudo echo "battle" > tweedle/beetle
-bash: tweedle/beetle: Permission denied
Without sudo, all is well:
$ cd ~
$ mkdir poodle
$ echo "noodle" > poodle/bottle
$ cat poodle/bottle
noodle
Thoughts?
The echo command is being run as root, but the redirection is done by your shell, so it's executed as the current user, not as root.
The simplest solution is to invoke a root shell to run both the command and the redirection.
Rather than:
sudo echo line > file
try this:
sudo sh -c 'echo line > file'
or
sudo bash -c 'echo line > file'
The answer is to use "tee" with a pipe, a command I wasn't familiar with, so you can use sudo for the second half:
$ echo "tweedle ALL=(ALL) ALL" | sudo tee /etc/sudoers.d/tweedle

Resources