Python和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!' 
  • 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
  • 30
  • 31
  • 32
  • 33
  • 34
  • 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
  • 30
  • 31
  • 32
  • 33
  • 34

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

  • 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
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 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
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98

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
  • 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
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 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
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

最后

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

转载:http://blog.csdn.net/jmilk/article/details/50680664

目录
相关文章
|
2月前
|
人工智能 运维 数据处理
PowerShell系列(二):PowerShell和Python之间的差异介绍
【1月更文挑战第4天】目前Python最火的编程语言,完整的生态、丰富的第三方资源库、丰富的社区文档教程,是目前人工智能、算法、数据处理分析等方面它属于最棒的编程语言,当然PowerShell作为微软官方推出的解释性语言,作为系统自动化运维脚本、数据处理分析语言还是非常值得学一学的。想对来说PowerShell目前的就业竞争小很多,未来还是非常有潜力的。
|
数据处理 Python Windows
Python Module_subprocess_调用 Powershell
目录 目录 前言 Powershell call Python Python call Powershell Powershell发送邮件 最后 前言 使用Python内建的subprocess模块,能够实现外部程序的调用。
1477 0
|
Python
python不同package下相互调用
路径如: /path/dir1/a.py /path/dir2/b.py   调用举例如: 在/path/dir2/b.py中调用 a模块   import sys sys.path.append("../") import dir1.a    
927 0
|
Java Shell Apache
使用thrift做c++,java和python的相互调用
linux上安装thrift见 http://jinghong.iteye.com/blog/1102535 thrift做为跨语言调用的方案有高效,支持语言较多,成熟等优点;代码侵入较强是其弱点。
1372 0
|
Python 数据格式 JSON
python调用powershell、远程执行bat
python调用本地powershell方法 1、现在准备一个简陋的powershell脚本,功能是测试一个IP列表哪些可以ping通: function test_ping($iplist) { foreach ($myip in $iplist) { ...
2877 0
|
2天前
|
网络协议 开发者 Python
深度探索Python Socket编程:从理论到实践,进阶篇带你领略网络编程的魅力!
【7月更文挑战第25天】在网络编程中, Python Socket编程因灵活性强而广受青睐。本文采用问答形式深入探讨其进阶技巧。**问题一**: Socket编程基于TCP/IP,通过创建Socket对象实现通信,支持客户端和服务器间的数据交换。**问题二**: 提升并发处理能力的方法包括多线程(适用于I/O密集型任务)、多进程(绕过GIL限制)和异步IO(asyncio)。**问题三**: 提供了一个使用asyncio库实现的异步Socket服务器示例,展示如何接收及响应客户端消息。通过这些内容,希望能激发读者对网络编程的兴趣并引导进一步探索。
11 4
|
1天前
|
网络协议 Python
网络世界的建筑师:Python Socket编程基础与进阶,构建你的网络帝国!
【7月更文挑战第26天】在网络的数字宇宙中,Python Socket编程是开启网络世界大门的钥匙。本指南将引领你从基础到实战,成为网络世界的建筑师。
6 2
|
2天前
|
开发者 Python
Python Socket编程:不只是基础,更有进阶秘籍,让你的网络应用飞起来!
【7月更文挑战第25天】在网络应用蓬勃发展的数字时代,Python凭借其简洁的语法和强大的库支持成为开发高效应用的首选。本文通过实时聊天室案例,介绍了Python Socket编程的基础与进阶技巧,包括服务器与客户端的建立、数据交换等基础篇内容,以及使用多线程和异步IO提升性能的进阶篇。基础示例展示了服务器端监听连接请求、接收转发消息,客户端连接服务器并收发消息的过程。进阶部分讨论了如何利用Python的`threading`模块和`asyncio`库来处理多客户端连接,提高应用的并发处理能力和响应速度。掌握这些技能,能使开发者在网络编程领域更加游刃有余,构建出高性能的应用程序。
10 3