术语“选择字符串”无法识别

时间:2019-06-12 01:28:07

标签: python powershell

我试图通过运行此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。 不太确定为什么它不适用于脚本,而是本身在命令提示符下起作用。

enter image description here

1 个答案:

答案 0 :(得分:0)

此问题特定于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以及一些其他零)

对我有用的内容-对于那些仅尝试获取PID并在python脚本中使用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的过程已终止

相关问题