Search code examples
linuxunixsshcommand-linesu

Unix: ‘su user’ not working and remains root inside SSH if condition


I've been working on bash script and have encoutered strange issue. Basically, I SSH into remote server as root from local server and trying to run some commands. One of the commands is changing the user to service account from root. For that I use command "su " and it changes to service account. But strangely, when I run the same command inside 'if condition', it remains as root account only. Here's the snippet of the code:

  echo "Enter host name you want to start: "
  read remote

  echo "Enter password for $remote : "
  read -s remote_pass

  sshpass -p$remote_pass ssh -T -o StrictHostKeyChecking=no $remote <<EOF
      ps -ef | grep -i tomcat | grep -i bootstrap | awk '{print \$2}'

      if [ -z "\$(ps -ef | grep -i tomcat | awk '{print \$2}')" ]
        then
          echo "$remote: Need to start server"
          su serviceAccount -----------> This doesn't work inside if controller
          startup.sh ---------> I want to run this script using serviceAccount and not as root!!!
        else
          echo "$remote: Already up and running"
      fi
      echo "#######################################################"
      echo
EOF

Please help!

Thanks, Sid


Solution

  • This is not strange but expected. su is not some kind of magic toggle, instead it spawns a new process with elevated rights. Everything you would like to do as serviceAccount needs to be done within the su call.

    For non-interactive use like in your example, the -c option comes handy:

    su -c 'startup.sh' serviceAccount