问题描述
当前,我正在使用 WMI库重新启动服务并从我的AWS实例收集参数。这是我实现重启服务的示例:
import wmi
import time
def connect_to_machine(ip):
connection = wmi.WMI(ip)
# example: connection = wmi.WMI("13.76.128.231",user=r"dileivas",password="P@ssw0rd@123")
return connection
def collect_running_services(connection):
print("Collecting running services in this machine...")
services = connection.Win32_Service(State="Running")
return services
def collect_stopped_services(connection,service_name,waiting_time):
print("Collecting stopped services in this machine...")
services = connection.Win32_Service(State="Stopped")
services_name_list = []
for service in services:
services_name_list.append(service.Name)
if service_name in services_name_list:
print(f'Found stopped service {service_name}!')
return services
else:
print(f"Service {service_name} still stopping. Waiting for more {waiting_time} seconds...")
time.sleep(waiting_time)
services = collect_stopped_services(connection,waiting_time) #Recursion
return services
ip_list = ['10.555.1.01','10.555.1.02','10.555.1.03']
service_name = 'WpNmRemote7140'
waiting_time = 10
# I'd rather stop and start the service than only restart it
for ip in ip_list:
print(f'Connecting to IP: {ip} ...')
connection = connect_to_machine(ip)
running_services = collect_running_services(connection)
for running_service in running_services:
if service_name in running_service.Name:
print(f'Stopping {running_service.Name} in {ip}...')
result = running_service.StopService()[0]
verify_result(result)
if result == 0:
print(f"Waiting for {waiting_time} seconds ...")
time.sleep(waiting_time)
stopped_services = collect_stopped_services(connection,waiting_time)
for stopped_service in stopped_services:
if service_name in stopped_service.Name:
print(f'Starting {stopped_service.Name} in {ip}...')
result = stopped_service.StartService()[0]
verify_result(result)
if result == 0:
print(f"{stopped_service.Name} was successfully restarted in {ip}!")
else:
print('An error has ocurred while trying starting the service.')
else:
continue
else:
print('An error has ocurred while trying stopping the service.')
print('\n')
因此,现在我发现了 psutil库,它似乎比WMI更好(并且在Linux OS中也可以使用)。我能否在上面显示的“ connect_to_machine(ip)”中连接AWS实例,而不是在每台机器上运行psutils?
非常感谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)