0

I am trying to SSH a client after i configured RSA connection. I would like to verify if SSH connection is successful, if yes then would like to source it first by calling a function then execute the command on client.Below is the script i am trying to execute on server,

function set_env() {
        if [ -f /usr/pw/server/bin/setup_env.sh ]; then
                        source /usr/pw/server/bin/setup_env.sh
        elif [ -f /etc/mcell/setup_env.sh ]; then
                        source /etc/mcell/setup_env.sh
        else
                        echo "setup_env.sh not found, exiting"
                        exit 1
        fi
}

i="application_was"

if ssh clientname
then
        set_env
        mcstat -q -n $i | grep "Running"
else
        echo "Sorry"
fi

I am able to SSH to the client but set_env function is not executed on the client upon login. How do i make sure it happens ? how to catch the error if it doesn't ?

1
  • Use expect(1) to script interactive programs. Commented Jan 7, 2015 at 17:40

1 Answer 1

2

Assuming this is all supposed to run on the remote machine then you need to put it all in the remote command.

When run in a non-interactive context ssh doesn't magicaly drop into a shell on the remote host for the rest of the running script (think about how that would need to work for a minute).

ssh clientname '
    if [ -f /usr/pw/server/bin/setup_env.sh ]; then
        source /usr/pw/server/bin/setup_env.sh
    elif [ -f /etc/mcell/setup_env.sh ]; then
        source /etc/mcell/setup_env.sh
    else
        echo "setup_env.sh not found, exiting"
        exit 1
    fi
    mcstat -q -n "'"$i"'" | grep "Running"' || echo "Sorry"

That will get you "Sorry" as output if the ssh connection fails or if the sourcing fails or if the grep fails and the output of grep in all other cases.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Etan Reisner, but it wouldn't hold variable value for i. Can i pass a variable in SSH command ?
Edited to use the variable from the current shell. Would probably be better to just inline the name in the command directly when possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.