【转载】Ansible-过滤危险命令

参考原文: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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值