#πŸ”’ adding and removing a firewall rule

4 messages Β· Page 1 of 1 (latest)

shell walrus
#

when i toggle to add rule it adds 1 rule but when i toggle to remove the rule it creates somehow 3 of them
⁨⁨⁨⁨```py
import keyboard, subprocess
settings = {"test": False}

firewall = {
"rule_name": "test",
"ip": "111.11.111.111",
"port": 80}

def add_test(rule_name, ip, port):
cmd = f'netsh advfirewall firewall delete rule name="{rule_name}"'
subprocess.run(cmd, shell=True, capture_output=True)
cmd = (
f'netsh advfirewall firewall add rule name="{rule_name}" '
f'dir=out action=block remoteip={ip} protocol=TCP remoteport={port}'
)
try:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode == 0:
print(f"Successfully created rule: {rule_name}")
return
else:
print(f"CMD Error: {result.stderr}")
print(f"CMD Output: {result.stdout}")
except Exception as e:
print(f"An error occurred: {e}")

def remove_test(rule_name):
cmd = f'netsh advfirewall firewall delete rule name="{rule_name}"'
subprocess.run(cmd, shell=True)
print(f"Rule {rule_name} deleted.")

def toggle_setting(setting, name, print_out):
settings[setting] = not settings[setting]
if print_out == True: print(f"{name} = {settings[setting]}")
if setting == "nosave":
if settings[setting] == True:
add_test(firewall['rule_name'], firewall['ip'], firewall['port']); return
else:
remove_test(firewall['rule_name']); return
return settings[setting]

def hotkeys():
def hotkey(button, setting, name, print_out): keyboard.add_hotkey(button, lambda: toggle_setting(setting, name, print_out))
hotkey("ctrl+f9", "test", "test", True)```⁩⁩⁩⁩
terminal:
test = True
Successfully created rule: test
test = False

Deleted 1 rule(s).
Ok.

Rule test deleted.

pearl sundialBOT
#

@shell walrus

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

pearl sundialBOT
#

@shell walrus

Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.