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

fnatzsnv  于 2023-04-21  发布在  Shell
关注(0)|答案(1)|浏览(147)

我尝试运行具有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```
x3naxklr

x3naxklr1#

方法的两个错误:

  • 【Python.文档】:subprocess.call(args,*,stdin=None,stdout=None,stderr=None,shell=False,cwd=None,timeout=None):

上面显示的参数只是一些常见的参数。完整的函数签名与Popen构造函数的签名相同...
,建议将参数指定为序列而不是字符串

#!/usr/bin/env python

import subprocess
import sys

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

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)
  • script00.ps1*:
${PSVersionTable}

输出

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

相关问题