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

所属分类: 脚本专栏 / PowerShell 阅读数: 288
收藏 0 赞 0 分享

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")

更多精彩内容其他人还在看

Powershell学习笔记--使用正则表达式查找文件

本文介绍PowerShell中使用正则表达式的查找文件的方法,PowerShell的正则表达式与微软其它语言的正则表达式是一样的,使用非常方便。
收藏 0 赞 0 分享

Windows Powershell 介绍和安装

Powershell 是运行在windows机器上实现系统和应用程序管理自动化的命令行脚本环境。微软之所以将Powershell 定位为Power,并不是夸大其词,因为它完全支持对象。其可读性,易用性,可以位居当前所有shell之首。
收藏 0 赞 0 分享

Windows Powershell 自定义控制台

这篇文章主要介绍了Windows Powershell 自定义控制台,包括选项、字体、布局和颜色四个方面的自定义风格,希望对大家有所帮助
收藏 0 赞 0 分享

windows Powershell 快速编辑模式和标准模式

powershell控制台有两种模式,一个是快速编辑模式,一个是标准模式。
收藏 0 赞 0 分享

PowerShell中查找字符串位置的IndexOf函数使用实例

这篇文章主要介绍了PowerShell中查找字符串位置的IndexOf函数使用实例,例子简单明了,容易看懂,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell使用正则表达式查找字符串实例

这篇文章主要介绍了PowerShell使用正则表达式查找字符串实例,主要是对match运算符的使用介绍,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell中使用正则表达式跨行匹配字符串的方法

这篇文章主要介绍了PowerShell中使用正则表达式跨行匹配字符串的方法,重点在于正则表达式的写法,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell中查看当前版本、Windows版本、.NET版本信息的代码

这篇文章主要介绍了PowerShell中查看当前版本、Windows版本、.NET版本信息的代码,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell 入门基础教程

Windows PowerShell 是专为系统管理员设计的新 Windows 命令行外壳程序。该外壳程序包括交互式提示和脚本环境,两者既可以独立使用也可以组合使用
收藏 0 赞 0 分享

PowerShell Contains函数查找字符串实例

这篇文章主要介绍了PowerShell Contains函数查找字符串实例,Contains函数的作用是查询一个字符串中是否存在另一个字符串,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多