简介:在进行一些涉及服务器或者PC主机的电源关机、开机、重启相关的测试中,远程开机或者唤醒,结合pythonping模块处理ping,可以节省出不必要的硬性等待时间,规避开机时间不稳定的情况,而且不会造成堵塞现象,易于提取。现提供一次性脚本给予各位看官参考。
历史攻略:
Python:用pythonping处理ping
测试网络连接:ping和telnet
gping:升级版ping可视化工具
远程开机:wakeonlan
IPMI开源库pyghmi基本使用
设计思路:
1、初始化为开机状态,支持唤醒或者远程开机
2、设置循环次数,循环开始
3、进行每一轮的指定测试内容
4、关机 或者 重启
5、设置必要的基础等待时间。为保护设备健康,强烈建议等待20 - 30秒
6、开机或者等待开机
7、ping目标主机,如果ping不通则等待10秒(可变),重复执行步骤6。
8、如果ping通,退出唤醒或者相关远程操作
9、重复执行 步骤 2 - 8
案例源码:
# -*- coding: utf-8 -*-
# time: 2024/4/15 21:38
# file: ping_demo.py
# 公众号: 玩转测试开发import time
import subprocess
from pythonping import pingdef sub(command, timeout=360):print(f"{command}")popen = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,universal_newlines=True, bufsize=1)out, err = popen.communicate(timeout=timeout)message = out + errprint(f"{message}")popen.kill()time.sleep(0.1)return popen, messagedef check_online(ip):message = ping(ip)print(message)success_ping = "Reply"if success_ping in str(message):print(f"Ping to {ip} success.")online_result = Trueelse:print(f"Ping to {ip} fail.")online_result = Falsereturn online_resultdef run(count):# initprint("do the init things.")for each_run in range(1, count + 1):print(f"The cycle {each_run} start")print("testing for something.")# shutdown or reboot# shell_command = "sudo shutdown -P now"# sub(f'ssh admin@10.11.12.13 "{shell_command}"')time.sleep(30)# shell_command = "wakeonlan 01:02:03:04:05:06"# sub(f'ssh admin@10.11.12.13 "{shell_command}"')target_ip = "10.11.12.13"wake_time_summary = 0while True:target_result = check_online(target_ip)if target_result:breakelse:time.sleep(10)wake_time_summary += 10# shell_command = "wakeonlan 01:02:03:04:05:06"# sub(f'ssh admin@10.11.12.13 "{shell_command}"')print(f"wake_time_summary:{wake_time_summary}")print(f"The cycle {each_run} finish.")if __name__ == '__main__':count = 2run(count)
运行结果: