A
A
Alexander Ananchenko2020-12-04 08:13:18
Python
Alexander Ananchenko, 2020-12-04 08:13:18

How to open and close ports through Python?

There is a PowerShell script for closing ports, is it possible to make the same script but in python?
I saw that it is possible to call PS commands through python, but this is not quite what I need

. This is what the script looks like in PowerShell:

Inclusion

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

New-NetFirewallRule -DisplayName "SPR1" -Direction Outbound -RemotePort 27000-27200,3097 -Protocol TCP -Action Block
New-NetFirewallRule -DisplayName "SPR2" -Direction Outbound -RemotePort 27000-27200,3097 -Protocol UDP -Action Block
New-NetFirewallRule -DisplayName "SPR3" -Direction Inbound -RemotePort 27000-27200,3097 -Protocol TCP -Action Block
New-NetFirewallRule -DisplayName "SPR4" -Direction Inbound -RemotePort 27000-27200,3097 -Protocol UDP -Action Block

Shutdown

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

Remove-NetFirewallRule -DisplayName "SPR1"
Remove-NetFirewallRule -DisplayName "SPR2"
Remove-NetFirewallRule -DisplayName "SPR3"
Remove-NetFirewallRule -DisplayName "SPR4"

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Amoralny, 2020-12-04
@Shurik24

The module import oshas a method system()that sends commands to the shell.

import os

request = ('...') # здесь код для открытия или закрытия портов
code = os.system(request)

print(code) # если выводит 0 - то успешно

You can also take a subprocess, namely, the call (request, shell = True) method

A
azarij, 2020-12-04
@azarij

due to my dull pythonic knowledge, I did not find how to directly control the firewall from python (you can, like, turn it on / off completely via wmi). however, to remove one level of abstraction, you can run not powershell commands from python, but netsh commands. and they can already steer the firewall as you like.
https://stackoverflow.com/questions/12381733/how-t... by the
way, if it's a matter of powershell cross-platform, then powershell core runs well on all sorts of linuxes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question