Question

I would test via a python script whether a passwordless ssh login has been setup or not. If i run the normal ssh command then it will wait to accept the password for some amount of time. Is there a way where the ssh command should return an error as soon as ssh asks for a password.

Is it possible to achieve this?

Was it helpful?

Solution

The ssh command accepts quite a large set of options, so assuming that your Python code is calling shell commands do the following :

ssh -oNumberOfPasswordPrompts=0 <host> "echo hello"

This will instantly fail if the keys have not been setup, and instantly complete if they have, which is the reason for the command being passed to the host. This gives you a simple test.

OTHER TIPS

paramiko will raise an AuthenticationException if you don't pass a password to the SSHClient's .connect() method and a working key cannot be found.

You can set a parameter to ssh command to only try the public key in the authentication process and set a batch mode with a command that always return true when the command is executed in the remote host. With that approach you can capture the exit code in the var $? and do some decision.

ssh -o PreferredAuthentications=publickey -o BatchMode=yes <host> /bin/true &> /dev/null
if [ $? -eq 0 ]; then
    #DO SOMETHING, THE CONNECTION WAS SUCCESSFUL
else
    #CONECTION DENIED
fi

You can capture custom output to a variable by finding the "Permission denied" in the verbose output of the ssh command as is in the following code.

PERMISION=$([ ! -z "$(ssh -v -o PreferredAuthentications=publickey -o BatchMode=yes <host> /bin/true 2>&1 | grep " Permission denied")" ] && echo "GRANTED" || echo "DENIED")
if [ $PERMISION == "GRANTED" ]; then
    #DO SOMETHING, THE CONNECTION WAS SUCCESSFUL
else
    #CONECTION DENIED
fi

I hope this find you useful .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top