-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirewall_allow.py
More file actions
37 lines (30 loc) · 1.23 KB
/
firewall_allow.py
File metadata and controls
37 lines (30 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import sys
from scriptlets._common.get_firewall import get_available_firewall
import subprocess
def firewall_allow(port: int, protocol: str = 'tcp', comment: str = None) -> None:
"""
Allows a specific port through the system's firewall.
Supports UFW, Firewalld, and iptables.
Args:
port (int): The port number to allow.
protocol (str, optional): The protocol to use ('tcp' or 'udp'). Defaults to 'tcp'.
comment (str, optional): An optional comment for the rule. Defaults to None.
"""
firewall = get_available_firewall()
if firewall == 'ufw':
cmd = ['ufw', 'allow', f'{port}/{protocol}']
if comment:
cmd.extend(['comment', comment])
subprocess.run(cmd, check=True)
elif firewall == 'firewalld':
cmd = ['firewall-cmd', '--permanent', '--add-port', f'{port}/{protocol}']
subprocess.run(cmd, check=True)
subprocess.run(['firewall-cmd', '--reload'], check=True)
elif firewall == 'iptables':
cmd = ['iptables', '-A', 'INPUT', '-p', protocol, '--dport', str(port), '-j', 'ACCEPT']
if comment:
cmd.extend(['-m', 'comment', '--comment', comment])
subprocess.run(cmd, check=True)
subprocess.run(['service', 'iptables', 'save'], check=True)
else:
print('No supported firewall found on the system.', file=sys.stderr)