python调用本地powershell

2023-01-31 05:01:17 python powershell 调用

# -*- coding: utf-8 -*-
import subprocess
 
def python_call_powershell(ip):
    try:
        args=[r"powershell",r"D:\jzhou\test_ping.ps1",ip]  #args参数里的ip是对应调用powershell里的动态参数args[0],类似Python中的sys.argv[1]
        p=subprocess.Popen(args, stdout=subprocess.PIPE)
        dt=p.stdout.read()
        return dt
    except Exception,e:
        print e
    return False
if __name__=="__main__":
    ip=["127.0.0.1"]
    print python_call_powershell(ip)

如果报错,说禁止执行脚本,是因为没有权限,所以,把上面的一行代码换成
 args=[r"C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe","-ExecutionPolicy","Unrestricted", r"D:\jzhou\test_ping.ps1",ip]


相关文章