Ansible 安全 之【过滤危险命令】

ansible对模块和命令做限制

vim /usr/local/python3/lib/python3.8/site-packages/ansible/playbook/play.py
...
from ansible.parsing.splitter import parse_kv
# 写在类的上面,否则调用不到(一定要写在全局)
def filter_cmd(data):
    filter_modules = ('command', 'shell', 'script', 'raw')
    filter_commands = ('rm -rf /','halt', 'poweroff', 'reboot', 'shutdown -h now','shutdown -r now','hostname')
    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, vars=None):
        if ('name' not in data or data['name'] is None) and 'hosts' in data:
            if data['hosts'] is None or all(host is None for host in data['hosts']):
                raise AnsibleParserError("Hosts list cannot be empty - please check your playbook")
            if isinstance(data['hosts'], list):
                data['name'] = ','.join(data['hosts'])
            else:
                data['name'] = data['hosts']
        filter_cmd(data)
        p = Play()
        if vars:
            p.vars = vars.copy()
        return p.load_data(data, variable_manager=variable_manager, loader=loader)

测试

ansible all -m shell -a "hostname"
# ERROR! Refused to execute the [hostname] command in the [shell] module.
ansible all -m shell -a "reboot"
# ERROR! Refused to execute the [reboot] command in the [shell] module.
ansible all -m shell -a "rm -rf /"
# ERROR! Refused to execute the [rm -rf /] command in the [shell] module.

测试ansible的yaml文件执行

cd /etc/ansible/ansible-playbook/
vim test.yml
- host: linux
  tasks:
    - name: test01
      shell: hostname

ansible-playbook test.yml 
# ERROR! Refused to execute the [hostname] command in the [shell] module.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值