有时候需要Python不能完成一些功能时,需要用到PowerShell的脚本,但是想要完成一个完整性功能,就需要在Python执行完会直接调用PowerShell脚本,以下举个例子来实现这个功能。

先写一个PowerShell的脚本:

PowerShell 测试Ping功能 #通过Python函数传进来的iplist进行Ping测试,并返回结果 function test_ping($iplist){ #$a = $iplist.split(",") foreach ($myip in $iplist) #foreach ($myip in $a){ $strQuery = "select * from win32_pingstatus where address = '$myip'" # 利用 Get-WmiObject 送出 ping 的查詢 $wmi = Get-WmiObject -query $strQuery if ($wmi.statuscode -eq 0) { echo "Pinging`t$myip...`tsuccessful" } else { echo "Pinging`t$myip...`tErrorCode:" + $wmi.statuscode } } } test_ping $args # -*- coding: utf-8 -*- import subprocess def python_call_powershell(ip): try: args = [r"powershell", r"D:/test_ping.ps1",ip] p = subprocess.Popen(args, stdout=subprocess.PIPE) dt = p.stdout.read()#这里是标准输出,也就是PowerShell输出什么都会被传递这里输出 return dt except Exception, e: print e return False if __name__ == "__main__": #ip = ["blog.bigyoung.cn", "blog.bigyoung.cn0", "3.3.3.3"] ip = '"blog.bigyoung.cn", "blog.bigyoung.cn0", "3.3.3.3"'#这里定义的IPlist 需要是一个str类型 # print python_call_powershell(",".join(ip)) print python_call_powershell(ip)

这个脚本的原理简单点就是通过Python的子进程调用Poweshell脚本,然后传回Ping结果。

具体的传参说明,需要进一步了解Python的subprocess第三方库。

参考文档:http://www.jb51.net/article/59292.htm

GitHub 加速计划 / po / PowerShell
44.27 K
7.16 K PowerShell/PowerShell: PowerShell 是由微软开发的命令行外壳程序和脚本环境,支持任务自动化和配置管理。它包含了丰富的.NET框架功能,适用于Windows和多个非Windows平台,提供了一种强大而灵活的方式来控制和自动执行系统管理任务。 最近提交 (Master分支:29 天前 )
a1774fd9 30 天前
5ad1f1d2 30 天前
  • 浏览量 7460
  • 收藏 0
  • 0

所有评论(0)