3

I am using following script to remote connection to a server and then if connection is successful then echoing success and if success then trying to sudo a file .If connection failed then it should echo FAIL. e.g

#!/bin/sh
ssh -t -t rxapp@$1
'if [$? -eq 0 ];
then
echo "SUCCESS"
sudo /etc/init/ntp $2
else
echo "FAIL: Couldnot connect to remote server"
fi'

Here $1 and $2 are given on command line . But this is not getting successful.Script only doing successful ssh but not running sudo and other echo commands. Output : Successful SSH but one exiting it showing following

./jenkins_ucf.sh: line 9: if [$? -eq 0 ];
then
echo "SUCCESS"
sudo /etc/init.d/unifiedCommFwk $2
else
echo "FAIL: COuldnot connect to remote server"
fi: No such file or directory

ANy help please ? or any alternative to it will be helpful too.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Kaku
  • 53
  • 2
  • 5
  • 10

4 Answers4

5
#!/bin/sh
ssh -t -t rxapp@$1 "echo SUCCESS; /etc/init/ntp $2" || echo "FAIL: Could not connect to remote server"

or with if:

if ssh -t -t rxapp@$1 "echo SUCCESS; /etc/init/ntp $2"; then
    echo SUCCESS
else
    echo "FAIL: Could not connect to remote server"
fi

You need to separate the parts that run on the remote server upon successful connection from the parts that run locally when the connection fails.

chepner
  • 497,756
  • 71
  • 530
  • 681
1

You don't need ' ' instead if you are trying to use backticks - that is not required either.

try this :

ssh -t -t rxapp@$1
if [ $? -eq 0 ];
then
echo "SUCCESS"
sudo /etc/init/ntp $2
else
echo "FAIL: Couldnot connect to remote server"
fi
cherry2891
  • 215
  • 1
  • 3
  • 13
0

You can execute an if else condition against an SSH server like so:

ssh user@host 'bash -s' <<'ENDSSH'
if [ someCommand ];
then
  echo "SUCCESS"
else
  echo "FAIL"
fi'
ENDSSH

Basically pulled from this answer

Community
  • 1
  • 1
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
-2

Simply do

ssh host -l username "if yourcommand; then echo Success; else echo Failure;fi"

For example

#!/bin/bash
CMD="if $1; then echo Success; else echo Failure; fi"
ssh host -l user "$CMD"
DusteD
  • 1,400
  • 10
  • 14