1
#!/bin/ksh
(some code)
Log=~/my.log
chown USER1 filename

su - USER1 -c "
date | tee -a ${Log} 2>&1; 
cd /blah/blah
if [ SOMECONDITION ]
then
sh ./somescript.ksh > logfile
fi
exit" | tee -a ${Log} 2>&1;

The script tends to stop when it swicthes to USER1 and then it executes again when we have to exit manually.

munish
  • 7,987

2 Answers2

2

I would expect that the script stops at the "su" command because it's prompting for a password and not getting one.

As often multiple solutions for that :)

Instead of "su" use "sudo" which has the -S switch to accept a password from standard input:

echo "password" | sudo -S -u USER1 sh -c "...

Alternatively move that section of your application/script that needs to run as a different user to a helper application. You can then avoid scripting with a stored clear text password (which has some security concerns) by using the set-uid and set-gid on that helper application:

chown USER1.GRP1 helperapp
chmod 6755 helperapp

The risk you run with this is that now anyone on the system can run helperapp as USER1. Instead of using set-uid/gid you can use configure sudo to allow a specific user to run het helperapp as USER1 without a password prompt (this requires admin/root priviliges):

# /etc/sudoers
# Allow USER2 to run helperapp as USER1 without prompting for a password
USER2 ALL=(USER1) NOPASSWD:/path/to/helperapp

your code can then look something like this:

#!/bin/ksh
(some code)
Log=~/my.log
chown USER1 filename

sudo -u USER1  /path/to/helperapp |  tee -a ${Log} 2>&1;

None of this was tested and use at your own peril...

HBruijn
  • 7,418
2

Since you are running su -, you are telling su to run a login shell. A login shell ignored its -c argument and reads commands interactively instead. The solution is to not pass -.

If you want to read the target user's startup file, do that explicitly.

su - USER1 <<EOF
date
if [ -e ~/.profile ]; then . ~/.profile; fi
…
EOF 2>&1 | tee -a -- "$LOG"