用ansible搜集机器的安全设置情况 + awk + sed
1.ansible的playbook
--- - name: a template example hosts: frame remote_user: root tasks: - name: max login try count shell: egrep -i 'MaxAuthTries' /etc/ssh/sshd_config |awk '{print $2}' register: try_count - name: ban root login from remote shell: egrep 'PermitRootLogin yes' /etc/ssh/sshd_config|wc -l register: PermitRootLogin - name: get PermitRootLogin result into template file template: src=/tmp/if_result.conf.j2 dest=/tmp/if_result.conf - name: use awk to print line number that line with sth wrong shell: awk 'NR>1{ if ($2!=$3)print "sed " NR"s%$%& not ok% /tmp/if_result.conf" >"/tmp/line_number.sh"}' /tmp/if_result.conf - name: modify the sed command shell: sed -i "s#sed#sed -i \'#" /tmp/line_number.sh - name: modify the sed command shell: sed -i "s#ok%#ok\'%#" /tmp/line_number.sh - name: add /bin/bash shell: sed -i '1i#/bin/bash' /tmp/line_number.sh - name: exec the script shell: /bin/bash /tmp/line_number.sh
2.jinja模板
[root@frontend-1 ~]# cat /tmp/if_result.conf.j2 metrics result standard MaxAuthTries {{try_count['stdout_lines'][0]}} 2 PermitRootLogin {{ PermitRootLogin['stdout_lines'][0] }} 0 my_ok 0 0
3.结果
[root@framework-1 tmp]# cat /tmp/if_result.conf metrics result standard MaxAuthTries 6 2 not ok PermitRootLogin 1 0 not ok my_ok 0 0
用一个例子来演示会更加清晰

浙公网安备 33010602011771号