Invoke PowerShell, remote execution bat file instance in Python _powershell

Source: Internet
Author: User
Tags in python

Python calls the local PowerShell method

1, now prepare a simple PowerShell script, the function is to test an IP list which can ping pass:

Copy Code code as follows:

function test_ping ($iplist)
{
foreach ($myip in $iplist)
{
$strQuery = "SELECT * from win32_pingstatus where address = ' $myip '"
# using Get-wmiobject to send a ping to the inquiry
$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's rudimentary invocation method:

Copy Code code as follows:

#-*-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], similar to the sys.argv[1 in Python]
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)

The following error may be reported (this may not be the problem if the server itself has permissions to run the PowerShell policy):

The second method of invocation can solve this method

2, when the call to set the PowerShell execution strategy, this method once the policy is set up, after the general, if necessary, and then in the PowerShell script finally add the policy has been changed back

Copy Code code as follows:

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, there is also one thing to note is that the PowerShell script must finally call its own function, and the function to have a return value so that Python can receive PowerShell script returned results, while PowerShell script calls function parameters are args[0] , Args[1], and so on, and then pass the corresponding arguments in the args in Python.

If you need to set the policy to the original default state, at the end of the PowerShell script, add the following: Set-executionpolicy restricted

Python remote invoke Bat execution command

1, first install the Python WMI package
2, the remote call bat is as follows:

Copy Code code as follows:

#-*-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 "Executed successfully!"
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")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.