python調用powershell、遠程執行bat


python調用本地powershell方法

1、現在准備一個簡陋的powershell腳本,功能是測試一個IP列表哪些可以ping通:

function test_ping($iplist)
{
    foreach ($myip in $iplist)
    {
        $strQuery = "select * from win32_pingstatus where address = '$myip'"
        # 利用 Get-WmiObject 送出 ping 的查詢
        $wmi = Get-WmiObject -query $strQuery
        if ($wmi.statuscode -eq 0) 
        {
            return "Pinging`t$myip...`tsuccessful"
        }
        else 
        {
            return "Pinging`t$myip...`tErrorCode:" + $wmi.statuscode
        }
    }
}

test_ping args[0]

python簡陋的調用方法:

# -*- coding: utf-8 -*-
import subprocess
 
def python_call_powershell(ip):
    try:
        args=[r"powershell",r"D:\jzhou\test_ping.ps1",ip]  #args參數里的ip是對應調用powershell里的動態參數args[0],類似python中的sys.argv[1]
        p=subprocess.Popen(args, stdout=subprocess.PIPE)
        dt=p.stdout.read()
        return dt
    except Exception,e:
        print e
    return False

if __name__=="__main__":
    ip=["1.1.1.1","2.2.2.2","3.3.3.3"]
    print python_call_powershell(ip)

可能會報下面的錯誤(如果服務器本身開啟了運行了powershell策略的權限可能沒有這個問題):

第二種調用方法可以解決這個方法

2、調用時設置powershell執行策略,這種方法一旦將策略設置好后,后面就通用了,如果需要的話再在powershell腳本最后加上已經將策略改回去

def python_call_powershell(ip):
    try:
        args=[r"C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe","-ExecutionPolicy","Unrestricted", r"D:\jzhou\test_ping.ps1",ip]
        p=subprocess.Popen(args, stdout=subprocess.PIPE)
        dt=p.stdout.read()
        return dt
    except Exception,e:
        print e
    return False

3、還有一點需要注意的是powershell腳本里最后必須要調用一下自己的函數,並且函數要有返回值,以便python能接收powershell腳本返回的結果,同時powershell腳本調用函數傳參的方式是args[0],args[1]等等,然后在python里的args里傳入對應的參數。

如果需要將策略設置為原來的默認狀態,在powershell腳本最后加上:Set-ExecutionPolicy Restricted

 

python遠程調用bat執行命令

1、首先安裝python的wmi包

2、遠程調用bat如下:

# -*- coding: utf-8 -*-
import wmi,json
import time

logfile = 'logs_%s.txt' % time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime())

#遠程執行bat文件
def call_remote_bat(ipaddress,username,password):
    try:
        #用wmi連接到遠程服務器
        conn = wmi.WMI(computer=ipaddress, user=username, password=password)
        filename=r"D:\apps\autorun.bat"   #此文件在遠程服務器上
        cmd_callbat=r"cmd /c call %s"%filename
        conn.Win32_Process.Create(CommandLine=cmd_callbat)  #執行bat文件
        print "執行成功!"
        return True
    except Exception,e:
        log = open(logfile, 'a')
        log.write(('%s, call bat Failed!\r\n') % ipaddress)
        log.close()
        return False
    return False

if __name__=='__main__':
    call_remote_bat(computer="192.168.1.2", user="testuser", password="testpwd")

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM