First, there is a big pain with regards to usage of remote ssh connections using and not using passwords in various companies, who claim to spend huge amount of time writing the right script to remotely connect with ssh, perform a command then check the return code and come back to the automation scripting tool :)
It took some time to gather, but I am going to show you a nice example of combining quite simple solution using Bash + Expect and one configuration parameter in /etc/ssh/ssh_config files. And it should run a remote command without asking a password or yes and no, check return code, and come back to you :)
First, configure on ssh client side, so it won’t ask you if you want to add a new key to your local keys repository, it is quite annoying question, most of they time you connect to your known servers, and perform automation operations, so you don’t need to check the key fingertip.
echo StrictHostKeyChecking no >> /etc/ssh/ssh_config
Second, you can detect if an existing (passwordless ssh keys are configured ignoring that script to perform the expect script).
#!/bin/bash
ip_address=”127.0.0.1″
user=”root”
user_password=”password”
command=”ls -la /tmp”
if ssh -o BatchMode=yes $ip_address true
ssh -o StrictHostKeyChecking=no $user@$ip_address $command
else
call_expect_function $user $ip_address “$command”
fi
# Here you would see how the temporary expect function is being created on each command call
call_expect_function () { # Function would accept $1 as user name, $2 ip address of remote ssh machine and $3 a command you need to send
# Creation of temporary file for run, note you need working expect package, on Debian, perform apt-get install expect
cat << SOF > /tmp/ssh_expect.exp
#!/usr/bin/expect -f
set timeout 35
set env(TERM)
spawn ssh -o StrictHostKeyChecking=no $1@$2 “$3; echo $\?”
expect “assword:” send “$user_password\r”
interact
SOF
chmod 755 /tmp/ssh_expect.exp # Set executable permission for temporary expect script.
/tmp/ssh_expect.exp | tee > /tmp/ssh_expect.out # This can be used for secondary logging purposes
cat /tmp/ssh_expect.out | sed -n ‘/password:/,//p’|grep -v password:|head -n -1 # This is used to actually see what is going on during the command on stdout cmd_result=`cat /tmp/ssh_expect.out | tail -1 | sed ‘s/[^0-9]//g’` # This is used to catch the remote return code and send it to ssh client
if [ $cmd_result -eq 0 ]; then # If the result is 0, then the remote command succeeded, else return 1
rm -rf /tmp/ssh_expect*
return 0
else
rm -rf /tmp/ssh_expect*
return 1
fi
}
Please shoot for questions!