系统环境:centos7
ansible playbook 编写
[root@control ansible]# cat 1-openFirewall.yml
---
- hosts: dlinux
remote_user: root
tasks:
- name: create new dir
file: path=/root/shell state=directory mode=0755
- name: copy shell script
copy: src=/root/shell/openFirewalld.sh dest=/root/shell/openFirewalld.sh mode=0711
- name: execute script
script: /root/shell/openFirewalld.sh
防火墙脚本编写
[root@control shell]# pwd
/root/shell
[root@control shell]# cat openFirewalld.sh
i#!/bin/bash
#用于centos7
#用于开启防火墙,打开防火墙中系统打开的端口
#备注:有些需要打开的端口,并没有监听,需要另行打开,如:ftp发送端口,可通过--add-service=ftp解决
#获取系统开启的端口号
getPort(){
portArray=()
num=0
for port in `ss -ntl|awk 'NR>1{print $4}'` #通过ss命令获取系统所有打开的端口
do
# echo ${port##*:}
portArray[$num]=${port##*:}
let num++
done
portArray=($(echo ${portArray[@]} |sed 's/ /
/g'|sort|uniq)) #对获取的端口进行去重
echo ${portArray[@]}
}
#输出系统开启的端口号
showOpenPort(){
portArray=($(getPort))
echo ${portArray[@]}
}
#开启防火墙,打开防火墙中系统打开的端口
openFirewalld(){
systemctl start firewalld
for port in `getPort`
do
firewall-cmd --permanent --add-port=${port}/tcp
done
firewall-cmd --reload
firewall-cmd --list-all
}
openFirewalld
执行ansible-playbook
ansible-playbook 1-openFirewall.yml