tgcloud
tgcloud

Reputation: 887

Python pexpect Check if server is up

I am automating few configuration steps on CentOS. In order to do so i need to reboot the system also. I am invoking the "reboot" command the via python pexepct, however i need to wait till the systems boots up for remaining script to executes. For that i am have written this small piece of code.

    while True:
        result = commands.getoutput("ping -c 4 192.168.36.134")
        if result.find("Unreachable") == 1:
            result = False
            print 'Rebooting the Systems.'
        else:
            result = True
            print 'Connected!'
            break

Is there any better way to do this? Also, can we achieve this with the pexepct itself?

Upvotes: 2

Views: 1762

Answers (1)

Oz Bar-Shalom
Oz Bar-Shalom

Reputation: 1855

You can try this:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# wait host to finish reboot, check specific port connection (usually ssh port if you want to exec remote commands)
while True:
    try:
        s.connect(('hostname', 22))
        print "Port 22 reachable"
        break
    except socket.error as e:
        print "rebooting..."
# continue
s.close()

This example is more effective then using ping

Upvotes: 3

Related Questions