I often need to determine if I can ssh into an IP address. In other world, for the server identified by the IP address, is the SSH port (22) is open?
First Attempt: Use bash and ssh
In my first attempt, I used the ssh
command from bash to check. This approach is not doable because I don’t know in advance the user name and password; all I know is the IP address.
Second Attempt: Use the socket Library
In this attempt, I use the socket library and attempt to connect to the IP address on port 22:
import socket def sshable(ip_address, port=22): """ Returns True if the IP address is ssh'able, False otherwise """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: return_code = sock.connect_ex((ip_address, port)) return return_code
Sample usage:
if not sshable("192.1.1.254"): print("Cannot ssh into address")
In the function above, note that I used the connect_ex method instead of connect. The difference is the former returns a none-zero error code upon failure; whereas the later will throw some exception.
Conclusion
Small functions like this is intuitive to look at, and if someone spend a few minutes to look up online would come up with it. The point here is to have it ready, when the need arise, I only need to copy it and use.