1

Im trying to categorize the files based on their permissions and I have a problem with the JSON query.

The output I like to categorize

Example

[email protected]:~$ stat -c '%a %n' $(pwd)/*
644 /home/user/go
755 /home/user/sshified
644 /home/user/test.yaml

or

[email protected]:~$ find / -perm -4000 -type f -exec stat -c '%a %n' {} 2>/dev/null \;
4755 /usr/bin/mtr
4755 /bin/su
4777 /bin/app1

The query which doesn't give any output back.

Ansible Code

   - 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}}
1
  • 1
    Instead of posting an image of code or output consider using the same format as your Ansible code, this is a better practice. Jan 13, 2022 at 15:25

2 Answers 2

1

Use find module and see what attributes are available in the registered results. For example, given the files

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

the debug below lists the registered attributes of the files

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

gives

  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]

For example, use the attribute wgrp to select group-writable files

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

gives

  msg:
  - test-476/test.yaml
0

If you just want to find files that are writeable, this can be much easier done on bash level:

   - 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
1
  • actually i want to do this '''find / -xdev ( -perm -4000 -o -perm -2000 ) -type f ! -path '/proc/*' -exec ls -l {} \; 2>/dev/null ''' and with json query to categorize them which are writeable or with execute rights
    – John Kon
    Jan 13, 2022 at 17:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.