【问题标题】:Trying to create service searcher尝试创建服务搜索器
【发布时间】:2021-07-24 12:29:12
【问题描述】:

我正在尝试编写一个 python 脚本,它将搜索 Windows 服务并在列表框中显示它们的名称、显示名称和状态,但到目前为止我所做的只会显示零。在下面的对话框中,我可以看到 3 个输出,但我不知道如何将它们放入下面的列表框中。

def search_query(searchbar):
    NameSave=("powershell -command "+'"'+"get-service *"+ searchbar+'* |ft -HideTableHeaders"')
    NameList=subprocess.call(NameSave, shell=True)
    serviceslist.insert(0,NameList)


searchf= tk.Frame(root, 
    bg="#20179a")
searchf.place(relx=0.5, 
    rely= 0.3, 
    relwidth=0.6, 
    relheight=0.075, 
    anchor="n")
searchbar= tk.Entry(searchf,
    font="Helvetica 18 bold",
    justify="center")
searchbar.place(relx=0.4,
    rely=0.5,
    relwidth=0.65, 
    relheight=0.8, 
    anchor="center")
searchbutton=tk.Button(searchf,
    text="Search Service",
    font="Helvetica 16 bold",
    fg="#20179a",
    bd=0,
    command= lambda: search_query(searchbar.get()))
searchbutton.place(relx=0.75,
    rely=0.5,
    relwidth=0.2,
    relheight=0.8, 
    anchor="w")



servicesf=tk.Frame(root,
    bg="#20179a")
servicesf.place(relx=0.05,
    rely=0.4,
    relwidth=0.9,
    relheight=0.45)
serviceslist=tk.Listbox(servicesf, font="Helvetica 18 bold")
serviceslist.place(relx=0.025,
    rely=0.1,
    relwidth=0.95,
    relheight=0.8)

Function for search

app design

【问题讨论】:

  • 我不明白为什么要为此任务编写 Python 脚本。可以在command prompt 窗口中分别执行sc query 和完整的限定文件名%SystemRoot%\System32\sc.exe query。此外,我不明白使用 Python 脚本有什么好处,该脚本使用了一个额外的脚本解释器(如 PowerShell)来执行主要任务,该任务使用 Windows 默认安装的最旧的脚本解释器运行,这是不必要的 - Windows 命令处理器cmd.exe。为什么要为一项任务使用三个脚本解释器?
  • 如果您想使用 Python 脚本捕获和显示 C:\Windows\System32\cmd.exe /c powershell -command "get-service *searchbar* |ft -HideTableHeaders" 的标准输出 stdoutsearchbar,我建议您仔细完整地阅读 subprocess module 的 Python 文档我们的未知字符串值和cmd.exe 搜索名称为powershell 的文件,希望找到%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
  • 我建议还仔细并完整地阅读有关 Windows 内核库函数 CreateProcess 的 Microsoft 文档,subprocess.run()、subprocess.call()` 和 subprocess.Popen() 在 Windows 上使用它来运行在shell=True 上,Windows 命令处理器cmd.exe 由环境变量ComSpec 定义,选项/c 和作为参数附加的命令行,发现powershell.exe 也使用CreateProcess 来运行PowerShell 可执行文件。跨度>
  • 在这种情况下,使用 cmd.exepowershell.exe 获取与通配符模式与变量 searchbar 的字符串值匹配的服务列表,这对您打开命令非常有用提示窗口,运行cmd /? 并仔细阅读输出帮助解释了不必要的使用Windows 命令处理器如何解释选项/c 之后的参数,这不容易理解,但在Python 代码中必须考虑。三种不同语法规则的三个脚本解释器的使用,真的不好处理。

标签: python-3.x windows powershell cmd scripting


【解决方案1】:

这个问题有一个 PowerShell 原生解决方案,只需几行代码。

Get-Service |Out-GridView -passthru `
   -Title "All Services on $($env:COMPUTERNAME), Select one or more for additional info" |
    Format-List 

生成此用户界面。

然后可以将结果存储在一个变量中以供以后使用,或者发送到另一个命令,例如Format-List

【讨论】:

    猜你喜欢
    • 2014-05-18
    • 2014-02-21
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    相关资源
    最近更新 更多