目录

前言

使用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来发送数据处理报告。实现的过程非常简便。

Python Module_subprocess_调用 Powershell的更多相关文章

  1. python调用powershell、远程执行bat

    python调用本地powershell方法 1.现在准备一个简陋的powershell脚本,功能是测试一个IP列表哪些可以ping通: function test_ping($iplist) { f ...

  2. python子类调用父类的方法

    python子类调用父类的方法 python和其他面向对象语言类似,每个类可以拥有一个或者多个父类,它们从父类那里继承了属性和方法.如果一个方法在子类的实例中被调用,或者一个属性在子类的实例中被访问, ...

  3. Python之调用函数

    Python之调用函数 Python内置了很多有用的函数,我们可以直接调用. 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数 abs,它接收一个参数. 可以直接从Python的官方网站查 ...

  4. Python下调用Linux的Shell命令

    有时候难免需要直接调用Shell命令来完成一些比较简单的操作,比如mount一个文件系统之类的.那么我们使用Python如何调用Linux的Shell命令?下面来介绍几种常用的方法: 1. os 模块 ...

  5. C#调用PowerShell脚本

    今天通过一个小例子,学习了C#如何调用PowerShell脚本文件的Function以及传参. private bool CallPowershell(string outputFile) { str ...

  6. Python脚本传參和Python中调用mysqldump

    Python脚本传參和Python中调用mysqldump<pre name="code" class="python">#coding=utf-8 ...

  7. python 可调用对象之类实例

    可调用对象,即任何可以通过函数操作符()来调用的对象. python可调用对象大致可以分为4类: 1.函数 python中有三种函数:内建函数(BIFs).用户自定义函数(UDF).lambda表达式 ...

  8. Django之在Python中调用Django环境

    Django之在Python中调用Django环境 新建一个py文件,在其中写下如下代码: import os if __name__ == '__main__': os.environ.setdef ...

  9. 在python里调用java的py4j的使用方法

    py4j可以使python和java互调 py4j并不会开启jvm,需要先启动jvm server,然后再使用python的client去连接jvm GatewayServer实例:允许python程 ...

随机推荐

  1. Spring基础20——AOP基础

    1.什么是AOP AOP(Aspect-Oriented Programming)即面向切面编程,是一种新的方法论,是对那个传统OOP面向对象编程的补充.AOP的主要编程对象是切面(aspect),而 ...

  2. SOA架构简介

    一. 什么是SOA 架构 SOA是一种架构模型,它可以根据需求通过网络对松散耦合的粗粒度应用组件进行分布式部署.组合和使用.服务层是SOA的基础,可以直接被应用调用,从而有效控制系统中与软件代理交互的 ...

  3. 创建AIX克隆盘

    1.AIX的克隆盘技术 AIX克隆盘,AIX rootvg的备用替换盘,可以用于保留AIX的原始状态,使AIX在进行升级操作时保留一个AIX操作系统的原始映像,在系统需要时实现即时还原,回到升级操作前 ...

  4. dedecms织梦无法保存栏目内容的解决方法

    最近使用DedeCms5.3和DedeCms5.5遇到了一个不可思议的问题:在添加栏目时IE内核的浏览器无法保存栏目内容.到网上搜索了半天没找到解决方法,查看DedeCms官方搜索到的结果是“栏目内容 ...

  5. 4.华为路由交换技术_IP路由选择原理(上)

    初始化时,路由表上只有直连路由 查看路由表 严格来讲任何一个具有三层路由功能的设备都有路由表 数据通信往往是双向的的,来回都要考虑. 路由是逐跳的,每一跳都要设置. 实际路由是根据已经分配的网络段进行 ...

  6. MyEclipse内存不足?这里有你想要的问题解决方案

    [MyEclipse CI 2019.4.0安装包下载] No.1 打开MyEclipse目录下的myeclipse.ini文件 在后面修改下面几个属性: vmargs Xms512m ( Java能 ...

  7. python实例31[生成随即的密码]

    代码: import random import string import time # strong.high = 3  #random for the whole passwd #storng. ...

  8. 【NOIP2016提高A组模拟9.15】Osu

    题目 分析 考虑二分答案, 二分小数显然是不可取的,那么我们将所有可能的答案求出来,记录在一个数组上,排个序(C++调用函数很容易超时,手打快排,时间复杂度约为\(O(>8*10^7)\),但相 ...

  9. 从fileGDB中获取List

    /// <summary> /// 从FGDB中获取 /// </summary> /// <param name="fileGDBPath"> ...

  10. js对象的创建模式

    方式一: Object构造函数模式 * 套路: 先创建空Object对象, 再动态添加属性/方法 * 适用场景: 起始时不确定对象内部数据 * 问题: 语句太多 /* 一个人: name:" ...