【问题标题】:WMI lib to start windows service remotelyWMI lib远程启动windows服务
【发布时间】:2017-12-15 15:09:28
【问题描述】:

如何使用 WMI 库启动服务? 下面的代码抛出异常:
AttributeError: 'list' object has no attribute 'StopService'

import wmi
c = wmi.WMI ('servername',user='username',password='password')
c.Win32_Service.StartService('WIn32_service')

【问题讨论】:

  • 引发了什么异常?请为您的问题添加完整的回溯。 'WIn32_service' 字符串参数中的字母大小写是故意的吗?

标签: python python-2.7 windows-services wmi


【解决方案1】:

github上有关于该库的文档:https://github.com/tjguk/wmi/blob/master/docs/cookbook.rst

我相信上面的代码会引发错误,因为您没有指定要启动哪个服务。

假设您不知道您可以使用哪些服务:

import wmi

c = wmi.WMI()  # Pass connection credentials if needed

# Below will output all possible service names
for service in c.Win32_Service():
    print(service.Name)

一旦您知道要运行的服务的名称:

# If you know the name of the service you can simply start it with:
c.Win32_Service(Name='<service_name>')[0].StartService()

# Same as above, a little differently...
for service in c.Win32_Service():
    # Some condition to find the wanted service
    if service.Name == 'service_you_want':
        service.StartService()

希望借助文档和我的代码 sn-ps,您将能够找到您的解决方案。

【讨论】:

  • 谢谢! - 我得到一个attributeError import wmi c = wmi.WMI ('servername',user='user',password='password') c.Win32_Service(Name='service_name').StartService() Traceback (最近一次调用最后一次) : Python Shell,提示 1,第 4 行 AttributeError: 'list' object has no attribute 'StartService'
  • 您是否将 'service_name' 作为实际服务名称传递?在我的代码中,我只是将其用作示例...通过库,您正在利用 Microsoft 的 Windows 查询语言,即您正在查询信息,而使用c.Win32_Service(Name='service_name'),您正在寻找名称为“service_name”的服务-我非常怀疑你的意图是什么。听起来您不确定要运行的服务的确切名称是什么 - 请参考我的第一段代码for service in c.Win32_Service(),运行此代码,查看输出,然后找到您想要的名称。跨度>
  • 我有一个实际的服务器名称、用户名、密码和服务名称。我刚刚编辑了帖子的“service_name”
  • 我编辑了我的答案,使其更加清晰 - 但是我现在知道问题所在,试试这个:c.Win32_Service(Name='&lt;service_name&gt;')[0].StartService()。在调用.StartService()之前需要先抓取查询返回的wmi对象;查询返回一个列表,其中包含 wmi 对象,因此[0] 变得必要。
  • 没问题 - 请将问题标记为已回答 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多