Ansible:如何按权限对文件进行分类?

Ansible: How to categorize files by permissions?

我正在尝试根据权限对文件进行分类 JSON 查询有问题。

我喜欢分类的输出

例子

user@test.example.com:~$ stat -c '%a %n' $(pwd)/*
644 /home/user/go
755 /home/user/sshified
644 /home/user/test.yaml

user@test.example.com:~$ find / -perm -4000 -type f -exec stat -c '%a %n' {} 2>/dev/null \;
4755 /usr/bin/mtr
4755 /bin/su
4777 /bin/app1

不返回任何输出的查询。

Ansible 代码

   - name: Find binaries with suid bit set 
     shell: 
       cmd: stat -c '%a %n' folder/* 
     register: files-with-write
     failed_when: files-with-write.rc != 1 and files-with-write.rc != 0
     changed_when: false

   - set_fact:
     writeable_files: "{{files-with-write| to_json | from_json |json_query(\"[?ends_with(mode, '7') == `true`].{gr_name: gr_name, mode: mode, path: path }\") }}"

   - debug:
     msg:
     - "files: {{writeable_files}}

如果您只想查找可写的文件,这在 bash 级别上可以更容易地完成:

   - name: Find writable by others
     command: find folder/ -perm /o+w 
     register: writable_others

   - name: Find writable by others or group
     command: find folder/ -perm /o+w,g+w 
     register: writable_others_group

使用像 find or stat 这样的 Ansible 模块,你可以用像

这样的东西开始你的实施
---
- hosts: test
  become: no
  gather_facts: no

  tasks:

  - name: Return a list of files
    find:
      paths: "/home/{{ ansible_user }}/"
      file_type: file
    register: result

  - name: Show result
    debug:
      msg: "{{ item.mode }} {{ item.path }}"
    when: item.mode == "0755"
    loop: "{{ result.files }}"

使用find模块,查看注册结果中有哪些属性可用。例如,给定文件

shell> stat -c '%a %n' test-476/*
644 test-476/go
755 test-476/sshified
664 test-476/test.yaml

下面的调试列出了文件的注册属性

    - find:
        paths: test-476
        recurse: true
      register: result
    - debug:
        var: result.files.0.keys()|list|to_yaml

给予

  result.files.0.keys()|list|to_yaml: |-
    [path, mode, isdir, ischr, isblk, isreg, isfifo, islnk, issock, uid, gid, size, inode,
     dev, nlink, atime, mtime, ctime, gr_name, pw_name, wusr, rusr, xusr, wgrp, rgrp,
     xgrp, woth, roth, xoth, isuid, isgid]

例如,使用属性wgrp到select组可写文件

    - set_fact:
        group_writeable_files: "{{ result.files|selectattr('wgrp') }}"
    - debug:
        msg: "{{ group_writeable_files|map(attribute='path')|list }}"

给予

  msg:
  - test-476/test.yaml