Powershell script converted to Python

Hey all!

I’ve written a PowerShell script that does the following:

Checks if a program is installed, uninstalls it if it is
Checks if a firewall rule with a variable defined name exists, deletes it if it is.
Downloads the program to the %TEMP% folder
Installs the program
Deletes the file from the %TEMP% folder
Creates a new firewall rule

I need a script that will duplicate this in Python for ITarian automation purposes.

For reference, here is the PowerShell script:

$file = '[filename]'
$link = '/$file'
$soft_name = '[Software Name]'
$fwStr = '[Firewall Rule Name]'
$fwPort = '[Firewall Port Range]'

$tmp = '$env:WinDir	emp\$file'
$find = Get-WmiObject -Class Win32_Product -Filter "Name LIKE `'$soft_name`%'"
$client = New-Object System.Net.WebClient
$firewallCheck = Get-NetFirewallRule | findstr '$fwStr'

[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12

if ($find -ne $null) {
$find.Uninstall()
echo "Uninstalled $soft_name"
}

if ($firewallCheck -ne $null) {
Remove-NetFirewallRule -DisplayName '$fwStr'
echo "Removed Extant Firewall Rule $fwStr"
}

$client.DownloadFile($link, $tmp)

Start-Process -FilePath "msiexec.exe" -ArgumentList "/i $tmp /qn" -Wait

del $tmp

echo "Installed $soft_name"

New-NetFirewallRule -DisplayName '$fwStr' -Direction Inbound -Action Allow -Protocol TCP -LocalPort $fwPort

echo "Added New Firewall Rule $fwStr to open inbount port(s) $fwPort"

Thanks!

Hi @SavageIT,

Thanks for your request. We have asked our script developers to check and provide feedback.

Kind Regards,
PremJK

Hi @SavageIT

If this is helpful to you, the easiest thing to do is to just run the powershell script from python instead of coverting the code directly. This assumes your only needing this to run on windows machines of course. I pretty much exclusively use powershell scripting for my ITSM procedures. Below is the python code I typically use

Just add your powershell script code between the quotes in ps_content=r"“” “”"

ps_content=r"""
#powershell script code goes here
"""

import os
print ("Powershell Script")
def ecmd(command):
import ctypes
from subprocess import PIPE, Popen

class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirect ion
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirecti on
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)

with disable_file_system_redirection():
obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
out, err = obj.communicate()
ret=obj.returncode
if ret==0:
if out:
return out.strip()
else:
return ret
else:
if err:
return err.strip()
else:
return ret

file_name='PowershellScript.ps1'
file_path=os.path.join(os.environ['TEMP'], file_name)
with open(file_path, 'wb') as wr:
wr.write(ps_content)

ecmd('powershell "Set-ExecutionPolicy RemoteSigned"')
print ecmd('powershell "%s"'%file_path)

os.remove(file_path)

Here is the an example using your provided powershell code:

ps_content=r"""
$file = '[filename]'
$link = '/$file'
$soft_name = '[Software Name]'
$fwStr = '[Firewall Rule Name]'
$fwPort = '[Firewall Port Range]'

$tmp = '$env:WinDir	emp\$file'
$find = Get-WmiObject -Class Win32_Product -Filter "Name LIKE `'$soft_name`%'"
$client = New-Object System.Net.WebClient
$firewallCheck = Get-NetFirewallRule | findstr '$fwStr'

[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12

if ($find -ne $null) {
$find.Uninstall()
echo "Uninstalled $soft_name"
}

if ($firewallCheck -ne $null) {
Remove-NetFirewallRule -DisplayName '$fwStr'
echo "Removed Extant Firewall Rule $fwStr"
}

$client.DownloadFile($link, $tmp)

Start-Process -FilePath "msiexec.exe" -ArgumentList "/i $tmp /qn" -Wait

del $tmp

echo "Installed $soft_name"

New-NetFirewallRule -DisplayName '$fwStr' -Direction Inbound -Action Allow -Protocol TCP -LocalPort $fwPort

echo "Added New Firewall Rule $fwStr to open inbount port(s) $fwPort"
"""

import os
print ("Powershell Script")
def ecmd(command):
import ctypes
from subprocess import PIPE, Popen

class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirect ion
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirecti on
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)

with disable_file_system_redirection():
obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
out, err = obj.communicate()
ret=obj.returncode
if ret==0:
if out:
return out.strip()
else:
return ret
else:
if err:
return err.strip()
else:
return ret

file_name='PowershellScript.ps1'
file_path=os.path.join(os.environ['TEMP'], file_name)
with open(file_path, 'wb') as wr:
wr.write(ps_content)

ecmd('powershell "Set-ExecutionPolicy RemoteSigned"')
print ecmd('powershell "%s"'%file_path)

os.remove(file_path)

I’ve also attached the above example procedure here: 20210225-SavageIT-Powershell-Script.json

Also as a quick note, I recommend replacing any “echo” commands in your powershell code and instead use “write-output”. I’ve noticed issues before using anything other than write-output where the text output may not display in the execution log of the procedure when wrapping powershell in python. Perhaps those issues were script specific but thought I’d share just in case.

Hope this is helpful!

20210225-SavageIT-Powershell-Script.json (3.38 KB)