Python Module_subprocess_调用 Powershell

目录

  • 目录
  • 前言
  • Powershell call Python
  • Python call Powershell
  • Powershell发送邮件
  • 最后

前言

使用Python内建的subprocess模块,能够实现外部程序的调用。如果你的工作环境是Windows系统,那么Python+Powershell的组合会为你的工作带来极大的便利。本篇介绍一个使用Python做数据处理,Powershell做系统调用的例子。

Powershell call Python

首先在Windows Server 2012 R2中使用Powershell脚本做数据收集,并存放到一个文件中。

#fileName = hd.ps1
#function for countdown
Function Countdown($number,$title,$text1,$text2='Pls Call Jmilk')
{
    Write-Host "Exit the Script after $number seconds" -ForegroundColor Red
    $Countdown = $number
    for($PercentComplete = $Countdown; $PercentComplete -ge 0; $PercentComplete--)
    {
        Write-Progress -Activity $title -Status $text1 -CurrentOperation $text2 -SecondsRemaining $PercentComplete ;
        Sleep -Seconds 1;
    }
}#End Function Countdown

Write-Host "Welcome to use the script to create table for HI & OFR nodes status" -ForegroundColor Cyan
Write-Host "Building the file hd.txt...Pls be patient.The script will be auto-Exit after created the hd.txt file" -ForegroundColor Yellow

#Change the rdtools path
$rdtoolsPath = 'E:\Users\userName\rdtools'
cd $rdtoolsPath

$cmd = 'commands'  #commands of Data-Collection 因为保密条约不能将内部指令对外 

cmd /c $cmd | Out-File -FilePath E:\Users\userName\Desktop\hd.txt
#在powershell里调用了别的Shell所以需要使用cmd指令来实现环境变量的传递
#Out-File 将数据导出到文件

Write-Host 'Build Done' -ForegroundColor Green

#Powershell call python
Start-Process python E:\Users\userName\Desktop\hd.py
#在收集完数据后调用Python做数据处理

#结束并推出Powershell
Countdown 60 'Hd.ps1' 'Exiting...' 'Pls go to the next step!' 

Python call Powershell

主要使用了subprocess模块,subproocess的详细介绍,点击这里

#coding:utf8
#FileName=hd.py

import os
import codecs
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.cell import get_column_letter
from openpyxl.cell import Cell
from openpyxl import Workbook
from openpyxl import load_workbook
import subprocess

#读取数据收集文件
def readFile(fileUrl):
    """Read the file and return the file content"""
    try:
        #unicode file
        fileObject = codecs.open(fileUrl,'r',encoding='utf-16')
    except unicodeDecodeError:
        print "Pls check the encoding for hd.txt whether [unicode]"
    else:
        print("Unspecified Error,Pls call Jmilk")

    try:
        fileContent = fileObject.readlines()
    finally:
        fileObject.close()
    return fileContent

#数据分类函数
def getNodeCountList(readLines):
    """Get the different node status type and change the global variable"""
    i = 0
    for line in readLines:
        lineItem = line.split(':')
        if lineItem[0] == '---- \r\n':
            i += 1
            continue
        if lineItem[0] == '  Node State':
            if lineItem[1] == ' Ready count':
                global ReadyCount
                ReadyCount[i-1] = int(lineItem[2])
            if lineItem[1] == ' OutForRepair count':
                global OutForRepairCount
                OutForRepairCount[i-1] = int(lineItem[2])
            if lineItem[1] == ' HumanInvestigate count':
                global HumanInvestigateCount
                HumanInvestigateCount[i-1] = int(lineItem[2])

#生成Excel表格
def createTable():
    """Create the HI‘s & OFR nodes status table"""
    wb = Workbook()
    ws = wb.worksheets[0]
    ws.title = u"NodeCount"
    for i in list(range(1,26)):
            ws.cell("A"+str(i)).value = '%s' % (cluster[i-1])
            ws.cell("B"+str(i)).value = '%s' % (HumanInvestigateCount[i-1])
            ws.cell("C"+str(i)).value = '%s' % (OutForRepairCount[i-1])
            ws.cell("D"+str(i)).value = '%s' % (ReadyCount[i-1])
            ws.cell("E"+str(i)).value = '%.2f%s' %((float(HumanInvestigateCount[i-1])/(HumanInvestigateCount[i-1]+OutForRepairCount[i-1]+ReadyCount[i-1]))*100,'%')
    wb.save("Hd.xlsx")

#Python call powershell 使用powershell实现发送数据处理邮件
def python_call_powershell(bodyStr):
        args = [r"C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe","-ExecutionPolicy","Unrestricted",r"E:\Users\userName\Desktop\SendMail.ps1",str(bodyStr)]
        ps = subprocess.Popen(args,stdout=subprocess.PIPE)
        psReturn = ps.stdout.read()
        return psReturn

if __name__ == '__main__':
    #Change to your user name
    user = 'userName'
    cluster = []
    ReadyCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    OutForRepairCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    HumanInvestigateCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    percentage = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

    fileUrl = 'E:\\Users\\' + user + '\\Desktop\\hd.txt'
    if os.path.exists(fileUrl):
        readContent = readFile(fileUrl)
        getNodeCountList(readContent)
        #createTable()
    else:
        print('Not exist the file!')
    for i in list(range(0,24)):
                percentage[i] = '%.2f%s' % ((float(HumanInvestigateCount[i])/(HumanInvestigateCount[i]+OutForRepairCount[i]+ReadyCount[i]))*100,'%')
    bodyStr = [x for li in [cluster,HumanInvestigateCount,OutForRepairCount,ReadyCount,percentage] for x in li]
    for index in list(range(0,24)):
                print cluster[index]+'\t',str(HumanInvestigateCount[index])+'\t',str(OutForRepairCount[index])+'\t',str(ReadyCount[index])+'\t'+percentage[index]
    print bodyStr

    callResult = python_call_powershell(bodyStr)
    print callResult

Powershell发送邮件

#fileName = sendMail.ps1

#Set secure password
Function Set-SecurePwd($storage)
{
    $mysecret = 'mailPassword'
    $mysecret |
    ConvertTo-SecureString -AsPlainText -Force |
    ConvertFrom-SecureString |
    Out-File -FilePath $storage

    $pw = Get-Content $storage | ConvertTo-SecureString

    return $pw
}#End Function Set-SecurePwd

#Sned Email
Function Send-Email($attach,$body)
{
    #$pwd = Set-SecurePwd $storage

    #$cred = New-Object System.Management.Automation.PSCredential "mailUsername",$pwd
    $to = "XXX@XXX.com"
    $from = "XXX@XXX.com"
    $cc = "XXX@XXX.com"
    $sub = "Number of statistics for Node status"
    $smtp = "SMTP.163.COM"

    Send-MailMessage -To $to -From $from -cc $cc -Subject $sub -Body  $body -BodyAsHtml  -SmtpServer $smtp -port 25 -Attachments $attach -Credential $cred -UseSsl 

    if($?)
    {
        Write-Host "Sent Successfully!" -ForegroundColor Green
    }
    else
    {
        Write-Host "Error" -ForegroundColor Red
    }
}#End Function Send-Email

#Mail
$storage = "E:\Users\userName\Desktop\password.txt"
$attach = "E:\Users\userName\Desktop\Hd.xlsx"
$data = $args[0]   #获取Python传递过来的参数
$date = Get-Date
$currentTime = "{0:G}" -f $date.AddHours(16)
$body = "<html>Report of data deal with</html>" #使用HTML的方式来自定义邮件格式

Send-Email $attach $body
Sleep 10

最后

在上面这个例子中,使用Powershell做数据收集,Python做数据处理,最后使用Powershell的内建方法Send-MailMessage来发送数据处理报告。实现的过程非常简便。

时间: 2024-09-11 16:59:22

Python Module_subprocess_调用 Powershell的相关文章

Python中调用PowerShell、远程执行bat文件实例_PowerShell

python调用本地powershell方法 1.现在准备一个简陋的powershell脚本,功能是测试一个IP列表哪些可以ping通: 复制代码 代码如下: function test_ping($iplist) {     foreach ($myip in $iplist)     {         $strQuery = "select * from win32_pingstatus where address = '$myip'"         # 利用 Get-WmiO

WF4.0 基础篇(二十八) WF调用PowerShell

PowerShell 提供了命令行管理系统的功能,但通常情况下,操作人员要完成某种业务需要多组PowerShell 命令,这样会很烦琐,错误率也比效高.操作人员可以编写powerShell脚本来组织命令,本文将介绍如何使用WF来 组织PowerShell命令,让操作人员只关心具体的命令,在一个可视化的流程设计器中组织命令间的逻辑关系 WF4.0中并没有提供调用powerShell的Activity,但可以使用中 Microsoft.Activities.PowerShell.Dll与 Invok

Python自动调用IE打开某个网站的方法

  本文实例讲述了Python自动调用IE打开某个网站的方法.分享给大家供大家参考.具体实现方法如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import win32gui import win32com import win32com.client import pythoncom import time class Test: def runtest(self): pri

.net-C#远程调用powershell访问lync服务器 报错问题

问题描述 C#远程调用powershell访问lync服务器 报错问题 如题,下面是代码和错误信息: 代码: string server = Convert.ToString(ConfigurationManager.AppSettings["serverName"]); string username = Convert.ToString(ConfigurationManager.AppSettings["userName"]); string str_passw

python学习-Python如何调用utilitytypes中的函数,急求!

问题描述 Python如何调用utilitytypes中的函数,急求! Python如何调用utilitytypes中的函数,急求,调用格式是什么,求大侠帮助,谢谢,急!!!!!! 解决方案 http://blog.163.com/xychenbaihu@yeah/blog/static/1322296552014829103732900/ 解决方案二: C++调用Python函数C++中调用python函数Python调用PHP的函数

python能否调用c++/cli的动态库(dll)

问题描述 python能否调用c++/cli的动态库(dll) 真心日了狗,有一个c#的dll,python无法直接调用c#的dll,于是想先让c++调用c#的dll,但是这需要使用c++/cli来实现,那么这样生成的c++/cli的dll,python能否调用... 解决方案 http://www.cnblogs.com/yinhaiming/articles/1599090.html 解决方案二: 楼上回答的很详细了,感觉可行,楼主试下! 解决方案三: 动态库DLL的调用调用本地方法(Dll

json-在国内python怎么调用googleapis?

问题描述 在国内python怎么调用googleapis? import urllib.request import urllib.parse import json url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=University+of+Salamanca' print('Retrieving', url) data = urllib.request.urlopen(url).rea

方法-Python如何调用C++dllku库。

问题描述 Python如何调用C++dllku库. 现在是报着错,但不知道怎么处理,百度网上的说方法1是调用方式,2是参数类型 但不知道怎么搞,求高手指教 我改成这样了就可以运行了,请问这个和我原来写的有什么区别呢? 解决方案 首先谢谢你的提示,我在修改后报出这个错误,百度未得,还请您指教 解决方案二: 用ctypes方式调用动态库,然后注意参数类型 Python调用windows下DLL详解 - ctypes库的使用

如何在python中调用ffmpeg的命令行语句

问题描述 如何在python中调用ffmpeg的命令行语句 问题是这样的:在ubuntu环境下,想在python程序中调用ffmpeg的一条命令: ffmpeg -i yourVideo.mp4 -vf select='eq(pict_type,I)' -vsync 2 -s 160x90-f image2 thumbnails-%02d.jpeg 在python程序中应该怎么写.哪位朋友能指导一下,十分感谢. 解决方案 可以用subprocess,https://docs.python.org