Reputation: 7226
I am trying to write a script that will server more as a health check or security test. I don't need to actually run anything via SSH.
We have a few servers running and for safety reasons we don't always allow SSH to them, and I would like to have a script that I could run that would confirm which are accessible and which are not.
I realize that StackExchange is filled with questions like these, so I quickly found this suggestion:
$ ssh -q user@downhost exit
$ echo $?
255
$ ssh -q user@uphost exit
$ echo $?
0
Basically it would return 255
whenever connection is not possible, but here is where I have an issue. Our servers require a key file AND user/password authentication.
Having BatchMode=yes
I could test it fine if I didn't have the password constraint as well.
I can give the script the location of the file, no problem there. But I get 255
every time because the server requires a password, as can be seen in this answer.
So basically my question is:
Is it possible to write a script that would let me know if it is possible to connect to these servers via SSH (given my constraints), and if it is what would that look like?
I don't need the final script as an answer (although that would be preferable). Just some pointers in the right direction would help me a great deal.
Thanks!
Upvotes: 4
Views: 8399
Reputation: 158080
You can use netcat
.
If you are just interested if the port is open you can use this:
if nc -w 5 -z "$server" 22 ; then
echo "Port 22 on $server is open"
fi
If you are also interested if there is actually an ssh daemon running on that port you may analyze the server's hello message:
if [[ $(nc -w 5 "$server" 22 <<< "\0" ) =~ "OpenSSH" ]] ; then
echo "open ssh is running"
fi
Btw, using the option -w
you can specify a connection timeout (in seconds). I've chosen 5 seconds for this example
Upvotes: 7
Reputation: 168
If you have valid key installed in your .ssh, you can use following (one time, not part of your script):
ssh-copy-id user@downhost
this will ask for your password and copies the key to server so that you can login without password from next time.
after that you should be able to run your command without password:
ssh -q user@downhost exit
hope it will help.
Upvotes: 1
Reputation: 61
Can you use "expect"(TCL)? If so, you could use a script like:
#!/usr/bin/expect
set timeout 6
set IP [lindex $argv 0]
spawn ssh -o StrictHostKeyChecking=no teste@$IP
expect "password:" {
send_user "\n1\n"
exit
}
send_user "\n0\n"
To run the script use:
./script.sh "SSH server IP"
This script will run expect and launch the ssh program connecting to the IP you passed on the 1st argument. If the "password:" prompt is returned to this script, it simply finishes. Of course this is just an idea, you must develop and parse content the script returns.
Upvotes: 3