Search code examples
bashsu

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:

  1. It has to be run as different user (user_B). Password needed here.
  2. 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 calling 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

Solution

  • #!/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