微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用psutil库

如何解决使用psutil库

当前,我正在使用 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 举报,一经查实,本站将立刻删除。