Python pexpect检查服务器是否启动
问题描述:
我正在CentOS上自动执行一些配置步骤。为了做到这一点,我需要重新启动系统。我正在调用通过python pexepct的“reboot”命令,但是我需要等待系统启动剩余的脚本才能执行。为此我写了这一小段代码。Python pexpect检查服务器是否启动
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
有没有更好的方法来做到这一点?另外,我们可以用pexepct本身来实现吗?
答
你可以试试这个:
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()
这个例子是更有效的再使用ping