如何使用Python中的参数运行PowerShell脚本

时间:2019-07-19 15:19:39

标签: python powershell command-line subprocess popen

我正在尝试运行具有Python 3.7.3中的参数的PowerShell脚本,但不知道如何在Popen中正确调用该函数

我要使用PowerShell脚本执行的操作是登录到Cisco路由器,并根据定义的路由器数量在x路由器上运行Cisco IOS命令。因此,我设置PowerShell脚本的方式是在使用PowerShell时传入路由器的IP地址,例如.\test.ps1 177.241.87.103,而在使用命令提示符时传入powershell.\test.ps1 177.241.87.103。这两个命令都可以工作并获得正确的输出,并将它们的输出也保存到文本文件中。

但是现在我想让Python使用参数运行此“ test.ps1”脚本。 我已经将“ test.ps1”保存到“ C:\ Users \ jgreen02”和“ C:\ Users \ jgreen02 \ Desktop”

import subprocess

subprocess.call("powershell .\\test.ps1 177.241.87.103")

我确定我没有正确使用call函数,或者也许我要运行的文件需要放在Python脚本所在的文件夹中。

错误输出为:

Traceback (most recent call last):
  File "C:/Users/jgreen02/PycharmProjects/PortChecker/Platypus.py", line 43, in <module>
    subprocess.call(["powershell test.ps1 10.238.241.38"])
  File "C:\Users\jgreen02\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 323, in call
    with Popen(*popenargs, **kwargs) as p:
  File "C:\Users\jgreen02\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Users\jgreen02\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified```

1 个答案:

答案 0 :(得分:0)

该方法有2处错误:

script.py

#!/usr/bin/env python3

import sys
import subprocess


def main():
    cmd = ["PowerShell", "-ExecutionPolicy", "Unrestricted", "-File", ".\\script.ps1"]  # Specify relative or absolute path to the script
    ec = subprocess.call(cmd)
    print("Powershell returned: {0:d}".format(ec))


if __name__ == "__main__":
    print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    main()
    print("\nDone.")

script.ps1

$PSVersionTable

输出

cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q057115405]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" script.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 64bit on win32


Name                           Value
----                           -----
PSVersion                      5.1.18362.145
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.18362.145
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1


Powershell returned: 0

Done.