Running interactive shell script in name of other user
In my shell script (bash) I want to call other shell scripts.
I run my script as user_A. One of these scripts needs special handling:- It has to be run as different user (user_B). Password needed here.
- It is interactive, but not only asks questions but runs another script in name of another user (user_C) using su. I have to enter a password here as well.
I can use su callin开发者_StackOverflowg this script but its questions have to be answered somehow. I can not enter anything because it prints for each questons "stty: : Not a typewriter"
I'm calling the special script this way
su user_B << ABC
...
special_script
...
ABC
#!/bin/bash
main_for_root(){
:
}
# ------------------------------------------------------------------------------
abs_path="$(readlink -f `dirname $0`)/$(basename $0)"
# if [ `id -u` != 0 ] ; then
if [ `whoami` != 'root' ] ; then
echo "[su -] run as root"
su -c"/bin/bash $abs_path $@"
exit 0
else
main_for_root $@
fi
It works for 1 user, so now add 'if ...' for second user
Another option for running scripts as other users is the 'sudo' command, think of it as 'superuser do:' for readability purposes. The -u parameter gives username information. So:
sudo -u user_B special_script
Will prompt for the password for user_B. I've never had a problem with running interactive programs using it. You can manage who can sudo to whom via the visudo command.
You can use sudo and create a sudoers file which allows user_A to run the script as user_B.
a line like:
user_A ALL = (user_B) NOPASSWD: /usr/share/stuff/ABC
would allow user_A to do something like
sudo -u user_B /usr/share/stuff/ABC
without asking for a password
su
attempts to get a password from the terminal and needs a tty device so it can call ioctl
to turn off key echoing. Since the standard input is coming from a "here document" (ABC), an attempt to call the ioctl on file descriptor 0 yields "not a tty".
If you must use a here document instead of a bona fide script, do:
cat > /tmp/myscript.$$ <<ABC
#!/bin/sh
...
ABC
chmod +x /tmp/myscript.$$
sudo -u user_B /tmp/myscript.$$
You may want to use expect
. Its designed for scripted interaction.
精彩评论