首页 > 解决方案 > 无法识别术语“Select-String”

问题描述

我试图通过运行这个 python 脚本来只获取 PID。

我目前的错误:

  1. 选择字符串未被识别为内部或外部命令
  2. 为了处理这个错误,我认为我需要逃避 | 通过添加 ^ --> 但显然它不起作用
  3. 我添加了一些 \ 来逃避“,希望它是正确的吗?

    cmd = "netstat -ano | findstr " + str(o)
    print (cmd)
    cmd += " | Select-String \"TCP\s+(.+)\:(.+)\s+(.+)\:(\d+)\s+(\w+)\s+(\d+)\" | ForEach-Object { Write-Output $_.matches[0].Groups[6].value }"
    print (cmd)
    
    pid = run_command(cmd)
    

run_command 方法执行此操作:

def  run_command(cmd_array,os_name='posix'):
    p = subprocess.Popen(cmd_array,shell=True,cwd=os.getcwd())
    output,err = p.communicate()
    print('output=%s'%output)
    print('err=%s'%err)
return output

预期结果

当我在命令提示符下单独运行命令时,它给了我 PID --> 在这种情况下为 7556。不太清楚为什么它不适用于脚本,而是单独在命令提示符下工作。

在此处输入图像描述

标签: pythonpowershell

解决方案


这个问题特定于 Windows 操作系统

回答我自己的问题

  1. 在评论的帮助下,我没有使用我的 run_command 方法,因为它使用的是 shell = True。

shell = True 指的是 Windows 上的 cmd.exe,而不是 powershell。我写的命令是powershell命令。

  1. 直接使用 subprocess.call 运行 powershell 命令

Python 脚本

cmd = "netstat -ano | findstr 8080"
cmd += " | Select-String \"TCP\s+(.+)\:(.+)\s+(.+)\:(\d+)\s+(\w+)\s+(\d+)\" | ForEach-Object { Write-Output $_.matches[0].Groups[6].value }"

subprocess.call(["powershell.exe", cmd])
#this does the job but the code will print extra zeros along with PID. It was not what i was looking for.

结果:

6492(打印出 PID 以及一些额外的零)

什么对我有用 - 对于那些试图在 python 脚本中使用 PID 只获取 PID 和终止端口的人

cmd = "for /f \"tokens=5\" %a in ('netstat -aon ^| find \":8080"
cmd += "\" ^| find \"LISTENING\"\') do taskkill /f /pid %a"

#I added in some \ to escape the "

run_command(cmd)

结果:

成功:PID 2072 的进程已终止


推荐阅读