天天看點

python調用powershell,f

複制

1、Get_RemoteAPP.ps1

set-executionpolicy remotesigned
Import-Module RemoteDesktopServices

function GetAPP(){
    $result = ls -l RDS:\RemoteApp\RemoteAppPrograms\
    $res = $result | ForEach-Object {$_.Name}
    return $res
}

GetAPP           

複制

2、New_RemoteAPP.ps1

set-executionpolicy remotesigned
Import-Module RemoteDesktopServices

$appList="C:\Program Files\PremiumSoft\Navicat Premium\navicat.exe","C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.2.3\bin\pycharm.exe","C:\Program Files\PremiumSoft\Navicat Premium\navicat.exe","C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.2.3\bin\pycharm.exe","C:\Program Files (x86)\Open×××\bin\open***-gui.exe","C:\Program Files (x86)\Mozilla Firefox\firefox.exe","C:\Program Files (x86)\KuGou\KGMusic\KuGou.exe","C:\Program Files (x86)\TeamViewer\TeamViewer.exe","C:\Program Files (x86)\Youdao\YoudaoNote\YoudaoNote.exe","C:\Users\Administrator.WIN-403TF0V1RLC\AppData\Local\youdao\dict\Application\YodaoDict.exe",""


function CheckAppPath($app)
{

    foreach($list in $appList){
        if ($list -like "*$app*"){
           $index = $list | % {[array]::IndexOf($appList,$_)}
           $appPath = $appList[$index]
       return $appPath
    }
    }
}

function New-RDSRemoteApp($appName)
{
    #傳回值說明:
    # 2 :程式已存在
    # 1 : 添加成功
    # 0 : 添加失敗

    if (Test-Path RDS:\RemoteApp\RemoteAppPrograms\$appName) {
        return 2
    }else {
    $appPath = CheckAppPath $appName
        New-Item -path RDS:\RemoteApp\RemoteAppPrograms -Name $appName -applicationpath $appPath >$null
        if (Test-Path RDS:\RemoteApp\RemoteAppPrograms\$appName) {
            return 1
        } else {
            return 0
        }
    }
}

New-RDSRemoteApp $args[0]           

複制

3、Remove_RemoteAPP.ps1

set-executionpolicy remotesigned
Import-Module RemoteDesktopServices

function RemoveAPP($appName){
    #傳回值0 :軟體不存在
    #傳回值1 : 删除成功
    #傳回值2 : 删除失敗
    if (-not (Test-Path RDS:\RemoteApp\RemoteAppPrograms\$appName)){
        return 0
    }else{
    Remove-Item -path RDS:\RemoteApp\RemoteAppPrograms\$appName -Recurse -Force -Confirm:$false | Out-Null
    if (-not (Test-Path RDS:\RemoteApp\RemoteAppPrograms\$appName)){
        return 1
    }else{
        return 2
    }
    
    }
}

RemoveAPP $args[0]           

複制

4、CallPowerShell.py

import subprocess
import json

def NewApp(param1):
    try:
        args = [r"powershell", r"C:\flask_remoteAPP_http\PosershellModule\New_RemoteAPP.ps1",param1]
        p = subprocess.Popen(args, stdout=subprocess.PIPE)
        dt = p.stdout.read()
        return dt
    except Exception, e:
        print e
    return False

def DelApp(param1):
    try:
        args = [r"powershell", r"C:\flask_remoteAPP_http\PosershellModule\Remove_RemoteAPP.ps1",param1]
        p = subprocess.Popen(args, stdout=subprocess.PIPE)
        dt = p.stdout.read()
        return dt
    except Exception, e:
        print e
    return False

def GetApp():
    try:
        args = [r"powershell", r"C:\flask_remoteAPP_http\PosershellModule\Get_RemoteAPP.ps1"]
        p = subprocess.Popen(args, stdout=subprocess.PIPE)
        dt = p.stdout.read()
        datalist = dt.split("\n")
        data = json.dumps(datalist)
        return data
    except Exception, e:
        print e
    return False

def QueryAllapp():
    f1 = open(r"C:\flask_remoteAPP_http\PosershellModule\appInventory.txt","r")
    data = {}
    appData = {}
    for i in f1.readlines():
        a = i.decode("gbk").split(",")
        data[a[1]] = a[0]
    appData["all"] = data
    jsondata = json.dumps(appData)
    return jsondata           

複制

5、run.py

from flask import Flask,request
import json
from CallPowerShell import NewApp,DelApp,GetApp,QueryAllapp


app=Flask(__name__)  

@app.route('/newapp', methods=['GET','POST'])  
def newapps():
    try:
        if request.method == 'POST':
            jsondata = request.get_data()
            dictdata = json.loads(jsondata)
            response = NewApp(dictdata["appName"])
            return response
            
        else:
            mes = '''
                <p><h1>Not Found</H1></p>
                <p>Request of this path cannot be found, or the server does not exist</p>
            '''
            return mes
        
    except Exception,error:
        print Exception,":",error
    

@app.route('/delapp', methods=['GET','POST'])  
def delapps():
    try:
        if request.method == 'POST':
            jsondata = request.get_data()
            dictdata = json.loads(jsondata)
            res = DelApp(dictdata['appName'])
            return res
        else:
            mes = '''
                <p><h1>Not Found</H1></p>
                <p>Request of this path cannot be found, or the server does not exist</p>
            '''
            return mes
    
    except Exception,error:
        print Exception,":",error


@app.route('/getapp')
def getapps():
    try:
        res = GetApp()
        return res
    
    except Exception,error:
        print Exception,":",error


@app.route('/queryall')
def queryalls():
    try:
        res = QueryAllapp()
        return res
    
    except Exception,error:
        print Exception,":",error
        
if __name__ == '__main__':  
    app.run(debug=True,host='0.0.0.0')           

複制

6、client.py

#coding:utf-8
import urllib2
import json

def newApp(appName):
    url = 'http://192.168.1.115:5000/newapp'
    #url = 'http://192.168.1.115:5000/delapp'
    data = {'appName': appName}
    headers = {'Content-Type': 'application/json'}
    req = urllib2.Request(url=url, headers=headers, data=json.dumps(data))
    response = urllib2.urlopen(req)
    return response.read()

def delApp(appName):
    url = 'http://192.168.1.115:5000/delapp'
    data = {'appName': appName}
    headers = {'Content-Type': 'application/json'}
    req = urllib2.Request(url=url, headers=headers, data=json.dumps(data))
    response = urllib2.urlopen(req)
    return response.read()

def getApp():
    url = 'http://192.168.1.115:5000/getapp'
    req = urllib2.Request(url=url)
    response = urllib2.urlopen(req)
    return response.read()

def queryAllApp():
    url = 'http://192.168.1.115:5000/queryall'
    req = urllib2.Request(url=url)
    response = urllib2.urlopen(req)
    return response.read()

if __name__ == "__main__":
    a = queryAllApp()
    b  = json.loads(a)
    print b           

複制

7、接口說明

1、添加APP接口

請求方式:POST

傳送資料類型:JSON

請求URL:http://192.168.1.115:5000/newapp

請求參數:{'appName':程式别名}

傳回資料類型:字元串

傳回結果:

傳回 "1" 添加成功

傳回 "2" 程式已存在

傳回 "0" 添加失敗

2、删除APP接口

請求方式:POST

傳送資料類型:JSON

請求URL:http://192.168.1.115:5000/delapp

請求參數:{'appName':程式别名}

傳回資料類型:字元串

傳回結果:

傳回 "1" 删除成功

傳回 "2" 删除失敗

傳回 "0" app不存在

3、擷取已添加的APP清單

請求方式:GET

請求URL:http://192.168.1.115:5000/getapp

請求參數:無參數

傳回資料類型:json

傳回資料:['app1','app2','app3']

4、擷取可進行添加的APP清單(包含已添加)的APP清單

請求方式:GET

請求URL:http://192.168.1.115:5000/getapp

請求參數:無參數

傳回資料類型:json

傳回資料:{'all':{'app1别名':'app1中文名','app2别名':'app2中文名'}}