有时候我们为了简便,部署服务的时候直接先关闭防火墙,后期再次开通防火墙,但是偶尔会有那么一两个遗忘,或者是怎么忘记的,这个时候我们就可以采用如下脚本来直接进行操作:
1、开启现在所有被占用端口的防火墙策略;
2、如果端口是123,说明是时间服务,我们给他udp协议;
#!/usr/bin/python
#coding:utf-8
import os
import linecache
os.system("netstat -tunlp | awk '{print $4}' | awk -F : '{print $2}' | grep -v '^#' | grep -v '^$' | uniq > 123.txt")
jier = linecache.getlines('123.txt')
for i in jier:
if str(i.strip()) == str('123'):
print("firewall-cmd --add-port={}/udp --permanent".format(i.strip()))
os.system("firewall-cmd --add-port={}/udp --permanent".format(i.strip()))
else:
print("firewall-cmd --add-port={}/tcp --permanent".format(i.strip()))
os.system("firewall-cmd --add-port={}/tcp --permanent".format(i.strip()))
os.system('rm -f 123.txt')
#os.system("firewall-cmd --add-port=22202/tcp --permanent")
os.system('firewall-cmd --reload')
os.system('firewall-cmd --list-port')