I'm trying a bash script where i'm taking an argument of a file which has the IP address. I'm using sshpass, but with this i'm not able to know if ssh login was successful or not. Is there a way to check this ? Please suggest if not sshpass, do i need to use any other cmd, to do remote login and execute cmds ?
Here is the snippet of the code :
#!/bin/bash
filename="$1"
while read -r line; do
sshpass -p 'test' ssh -o StrictHostKeyChecking=no test@$line 'df -h'
done < "$filename"
Have tried the suggested way to check $? value (if its incorrect password, $? value will be 5, however with valid or invalid password, shell script is not echoing 'wrong password', its always echoing "Can ssh to box- Password is correct" as per the following code :
#!/bin/bash
filename="$1"
while read -r line; do
sshpass -p 'test' ssh -o StrictHostKeyChecking=no test@$line 'df -h'
if [ $? -eq 5]
then
echo "Wrong password"
else
echo "Can ssh to box- Password is correct"
fi
done < "$filename"
My Requirement is to ssh to the remote box and execute commands. And in case, ssh fails i.e password is invalid, it need to print that password is invalid.
Use return value from sshpass
.
According to man sshpass
:
RETURN VALUES
As with any other program, sshpass returns 0 on success. In case of failure, the following return codes are used: 5 Invalid/incorrect password
After running sshpass
, in bash return value from command is stored in $?
variable.
Proof:
devilan@localhost:~ $ sshpass -p 'test' ssh smurf@localhost
devilan@localhost:~ $ echo $?
5
Sugested usage:
sshpass -p 'test' ssh smurf@localhost
if [ $? -eq 5 ]
then
echo "Wrong password"
else
echo "Something else"
fi