Home > OS >  bash script to log as another user and keep the terminal open
bash script to log as another user and keep the terminal open

Time:03-25

I have set up a http server at localhost, with several sites. I would like to connect to each site root folder, at the same way I used to at a remote server via ssh. So, I tried to create a bash script, intended to log as user "http", giving the site root folder as argument and change the $HOME to the site root folder:

#!/bin/bash
echo "Connecting to $1 as http...";
read -p "Contraseña: " -s pass;
su - http << EOSU >/dev/null 2>&1
$pass
export HOME="/srv/http/$1";
echo $HOME;
source .bash_profile;
exec $SHELL;
EOFSU

It does not work, basically because of:

  1. echo $HOME keeps giving out the home folder of the user launching the script.
  2. when the script reaches the end, it ends (obvious), but I would like that it stays open, so I could have a terminal session for user "http" and go on typing commands.

In other words, I am looking for a script that saves me 3 commands:

# su - http
# cd <site_root_folder>
# export HOME=<site_root_folder>

CodePudding user response:

If you need to script some commands and then change to an interactive session then pyexpect would be your best solution.

This example may give you some ideas.

CodePudding user response:

Your main problem is that the $HOME is evaluated as when the user run the script, meaning that it will get his evaluation of $HOME instead of evaluating it as the given user.

You can evaluate the $HOME as the given user (using the eval command) but I wont recommend it, it is generally bad practice to use this kind of evaluation, especially when talking about security.

I can recommend you to get the specific user home directory with standard linux tools like passwd

Example of the behavior you are seeing:

# expected output is /home/eliott
$ sudo -u eliott echo $HOME
/root

Working it around with passwd:

$ sudo -u eliott echo $(getent passwd eliott | cut -d: -f6)
/home/eliott

CodePudding user response:

Here's a way to do it with a bash init file generated on-the-fly:

#!/bin/bash

su http -- --init-file <(cat <<EOF
    export HOME=$(printf '%q' "/srv/http/$1")
    cd "\$HOME"
    . .bash_profile
EOF
)
notes:
  • With a bash init file you have to use su http instead of su - http

  • For expanding $1 in your context you need to escape it with printf '%q' "$1"

  • As you don't want $HOME to be expanded by the current shell, you need to write it as \$HOME in the here-document

  •  Tags:  
  • bash
  • Related