有时候需要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不能完成一些功能时,需要用到PowerShell的脚本,但是想要完成一个完整性功能,就需要在Python执行完会直接调用PowerShell脚本,以下举个例子来实现这个功能。先写一个PowerShell的脚本: PowerShell 测试Ping功能 PowerShell #通过Python函数传进来的ipli...
在server程序运行到一半或者要结束的时候希望它自动记录下当前server的状态,包括有多少个进程,每个占多少CPU,多少内存,系统还剩多少内存之类的。
很简单,既然程序有
python
脚本
,那么就通过
python
脚本
开一个进程运行一些power shell的
脚本
,把结果写文件。
PowerShell
花了一天时间,啃了点文档,记录一些例子:
获取帮助:get-help...
像运行可
执行
文件一样,
Powershell
运行文件和
脚本
,也必须使用绝对路径或者相对路径,或者要运行的文件必须定义在可受信任的环境变量中。
脚本
:
脚本
和批处理都属于伪可
执行
文件,它们只是包含了若干命令行解释器能够解释和
执行
的命令行代码。
执行
批处理文件:批处理是扩展名为”.bat”的文本文件,它可以包含任何cmd控制台能够处理的命令。当批处理文件被打开,Cmd控制台会逐行
执行
每条命令。
在P...
foreach ($myip in $iplist)
$strQuery = “select * from win32_pingstatus where address = ‘$myip'”
# 利用 Get-WmiObject 送出 ping 的查詢
$wmi = Get-WmiObject -query $strQ
#
执行
PowerShell
命令
result = subprocess.run(['
powershell
', '-Command', command], capture_output=True)
# 输出结果
print(result.stdout.decode('utf-8'))
在上面的代码中,我们使用subprocess.run()函数来
执行
PowerShell
命令。该函数的第一个参数是一个列表,其中包含要
执行
的命令和参数。在这个例子中,我们将
PowerShell
命令作为字符串传递给变量command,然后将其作为参数传递给subprocess.run()函数。我们还将capture_output参数设置为True,以便将命令的输出捕获到result变量中。最后,我们使用print()函数输出结果。
请注意,如果要在
PowerShell
中
执行
多个命令,可以将它们放在一个字符串中,用分号分隔。例如:
```
python
command = 'Get-Process; Get-Service'