欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > Ubuntu ufw + Python3 add / remove port-rule

Ubuntu ufw + Python3 add / remove port-rule

2025/2/25 4:42:01 来源:https://blog.csdn.net/qq_21264377/article/details/144253787  浏览:    关键词:Ubuntu ufw + Python3 add / remove port-rule

Ubuntu ufw + Python3 add / remove port-rule

# Ubuntu 24.04
# 查看防火墙状态
~$ sudo ufw status
# 启用ufw防火墙
~$ sudo ufw enable
# 关闭ufw防火墙
~$ sudo ufw disable
# 重载ufw防火墙
~$ sudo ufw reload
# 防火墙禁止接收http数据包
# http端口号为80
~$ sudo ufw reject http
# 防火墙禁止发送http数据包
~$ sudo ufw reject out http
# 防火墙禁止接收https数据包
# https端口号为443
~$ sudo ufw reject https
# 防火墙禁止发送https数据包
~$ sudo ufw reject out https
# 显示ufw防火墙状态和带编号策略
~$ sudo ufw status numbered
# 删除第1条策略
~$ sudo ufw delete 1
# sudo ufw status numbered | grep '80'
# sudo ufw status numbered | grep '443'
# 显示有关80或443端口的ufw防火墙策略
sudo ufw status numbered | grep '80\|443'

一键添加禁止http/https数据包的策略,保存为addhttpsrule.sh,Ubuntu下使用命令行source addhttpsrule.shsh addhttpsrule.sh执行

#
# File: addhttpsrule.sh
# Author: Nega
# Created: 11/5/24 Tue.
# 
#!/bin/bash
echo 'addrule reject-http-in..'
sudo ufw reject in http
echo 'addrule reject-http-out..'
sudo ufw reject out http
echo 'addrule reject-https-out..'
sudo ufw reject out https
echo 'addrule reject-https-in..'
sudo ufw reject in https
sudo ufw status numbered | grep '80\|443'

Python代码删除ufw防火墙禁止http/https的策略:

'''
@file: removehttpsrule.py
@author: Nega
@created: 11/5/24 Tue.
@description: None
'''
#!/bin/python3import os
import redef __auto_remove_https_rules(port=80):p = os.popen('sudo ufw status numbered | grep ' + str(port))if p is None:print('[TEST] aborted, with no return')returnr = p.read()if r is None:print('[TEST] no read data')returnr = r.strip()if '\n' in r:r = r.replace('\n', '')if r == '':print('[SKIP] no rule matching port ' + str(port))MAX_TRIES = 4count = 0while r != '' and count < MAX_TRIES:try:count += 1did = re.findall('\\[[ ]?([0-9]+)\\]', r, re.M | re.I | re.S)[0]print('sudo ufw delete [' + did + '] port=' + str(port))os.system('sudo ufw delete ' + did)p = os.popen('sudo ufw status numbered | grep ' + str(port))r = p.read()r = r.strip().replace('\n', '')except Exception as err:r = ''print('[ERR] error occurred, ' + str(err))if __name__ == '__main__':__auto_remove_https_rules(80)__auto_remove_https_rules(443)os.system('sudo ufw status numbered | grep "80\\|443"')

removehttpsrule.sh:

#
# File: removehttpsrule.sh
# Author: Nega
# Created: 11/5/24 Tue.
# 
#!/bin/bash
if test -f /usr/bin/python3;then
python3 removehttpsrule.py
else
echo 'no python3'
fi

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词