I've written expect and bash scripts to work this.... (though it can get fancier as mentioned above).
Bash script:
executed with three arguments: user, pass, and host. For example ./bwrap.sh ninja_user ninja_star1234 ninja.com
The script creates a log file which later used for checking successful log in/out.
#!/bin/bash
# log file
log="connection_test.log"
if [ -f $log ];
then
echo "Older file $log exists, removing and creating new..."
rm -rf $log
touch $log
else
echo "Creating log file"
touch $log
fi
# running expect script.
# arg 1 is user, arg 2 is pass, arg 3 is host
./one.exp $1 $2 $3 >> $log
# checking log for connections
if grep --quiet logout $log; then
echo "connection successful, proceeding to backup" >> $log
else
echo "connection failed, please check server" >> $log
exit 1
fi
Now to the expect script, it has a timeout of 10 seconds, and I actually prefer to work w/o strict host key. If you do want to work with strict host key edit the relevant line and add an expect "yes/no" ....
#!/usr/bin/expect -f
set user [lindex $argv 0];
set password [lindex $argv 1];
set host [lindex $argv 2];
set timeout 10
# now ssh
spawn ssh $user@$host -o StrictHostKeyChecking=no
match_max 100000 # Look for passwod prompt
expect "*?assword:*"
# Send password aka $password
send -- "$password\r"
expect "*$ "
send -- "whoami\r"
expect "<user name>" # change user
send -- "exit\r"
expect eof
Hope this helps.
For sftp connection please:
add line to bash script where $4 is port
./one.exp $1 $2 $3 $4 >> $log
add line to expect script:
set port [lindex $argv 3];
replace in expect script
spawn ssh $user@$host -o StrictHostKeyChecking=no
with
spawn sftp $host@$user -o Port=$port StrictHostKeyChecking=no
and
expect "*$ "
with
expect "sftp>"
Since I do not have an SFTP server to test it on, the changes are made based on [this question]: sftp a file using shell script
Also, [expect homepage]: http://expect.sourceforge.net/ might be handy.
Lastly, reading your comment regarding a straight forward approach, it's possible to simply use nc and see if the host:port is up. For this you can use:
#!/bin/bash
# log file
log="connection_test.log"
if [ -f $log ];
then
echo "Older file $log exists, removing and creating new..."
rm -rf $log
touch $log
else
echo "Creating log file"
touch $log
fi
# nc
nc_command=`nc -z -w 5 $1 $2 | tee -a $log`
if [[ $nc_command == *succeeded* ]];
then
echo "Server is listening, ready for backup" | tee -a $log
else
echo " Server seems to be offline, please check" | tee -a $log
exit 1
fi
To run the last script use: ./test.sh host port
expect/tclwhich never becomes elegant, as it is very hard to parse text and foresee any possible error conditions before you have found them the first time. Using for examplelftp, the client itself checks the sftp-protocol's built-in status response codes. This makes catching errors easy.