参考原文:Ansible 安全 之【过滤危险命令】 - 简书
通过新增过滤代码过滤危险命令
如果是用非虚拟环境virtualenv安装,则需要修改的文件位置如下:
/usr/local/python3/lib/python3.8/site-packages/ansible/playbook/play.py
如果使用了虚拟环境virtualenv安装,则需要修改的文件在虚拟环境目录下。如:
/opt/Python3.10.4/ansible5.6/lib/python3.10/site-packages/ansible/playbook/play.py
在文件顶部引入需要的模块
from ansible.parsing.splitter import parse_kv
在Play类的上方新增函数
def filter_cmd(data):
filter_modules = ('command', 'shell', 'script', 'raw')
filter_commands = ('rm -rf /','halt', 'poweroff', 'reboot', 'shutdown -h now','shutdown -r now')
filter_commands = map(lambda x:x.replace(' ', '').lower(), filter_commands)
for t in data['tasks']:
if'action' in t:
if t['action']['module'] in filter_modules:
if t['action']['args']['_raw_params'].replace(' ', '').lower() in filter_commands:
raise AnsibleParserError("Refused to execute the [%s] command in the [%s] module." % (t['action']['args']['_raw_params'], t['action']['module']))
else:
for m in filter_modules:
if m in t:
args=parse_kv(t[m], check_raw=True)
if args['_raw_params'].replace(' ', '').lower() in filter_commands:
raise AnsibleParserError("Refused to execute the [%s] command in the [%s] module." % (t[m], m))
在Play类的load方法中引用filter_cmd过滤命令
在p = Play()上方添加filter_cmd(data)
@staticmethod
def load(data, variable_manager=None, loader=None):
if ('name' not in data or data['name'] is None) and 'hosts' in data:
if isinstance(data['hosts'], list):
data['name'] = ','.join(data['hosts'])
else:
data['name'] = data['hosts']
filter_cmd(data)
p = Play()
return p.load_data(data, variable_manager=variable_manager, loader=loader)