Using PHP to check SSHD availability

I’m working on a project where I need to spin up some EC2 instances and deploy code to them over SSH which requires that I know when SSH is available. To do this, I’ve written a little PHP snippet that will connect to the server via TCP port 22 and loop until the service is available:

        $address   = "" ;
        $port         = 22 ;
        $sleeptime = 1 ;

        $resource = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ) ;
        while ( ! @socket_connect( $resource, $address, $port ) ) {
                print "not ready\n" ;
                sleep( $sleeptime )  ;

        print "ready\n" ;

Note the @ sign in front of the socket_connect function call to suppress PHP Warnings when it fails. This is because I expect it to fail 99% of the time.






Leave a Reply

Your email address will not be published. Required fields are marked *