Linux命令将用户及其组用于Ansible的特定输出

时间:2018-05-15 12:27:38

标签: linux shell ansible

我有以下输出:

dante
Last password change                    : Aug 18, 2017
Password expires                    : never
Password inactive                   : never
Account expires                     : never
Minimum number of days between password change      : 0
Maximum number of days between password change      : 99999
Number of days of warning before password expires   : 7
Linux shell                                         : /bin/bash

marion
Last password change                    : Aug 28, 2017
Password expires                    : never
Password inactive                   : never
Account expires                     : never
Minimum number of days between password change      : 0
Maximum number of days between password change      : 99999
Number of days of warning before password expires   : 7
Linux shell                                         : /bin/bash 

使用以下命令完成此输出:

cat /etc/passwd | xargs -n1 -I{} bash -c 'a=`echo "{}" | cut -f1 -d:`; echo -e "\n$a"; chage -l $a; echo -e "Linux shell\t: " `echo "{}" | cut -f7 -d:`' >> users-list.log

我需要获取每个用户名并添加属于user-list.log的组。例如:

dante
Last password change                    : Aug 18, 2017
Password expires                    : never
Password inactive                   : never
Account expires                     : never
Minimum number of days between password change      : 0
Maximum number of days between password change      : 99999
Number of days of warning before password expires   : 7
Linux shell                                         : /bin/bash
Groups                                              : dante, prime, trm

marion
Last password change                    : Aug 28, 2017
Password expires                    : never
Password inactive                   : never
Account expires                     : never
Minimum number of days between password change      : 0
Maximum number of days between password change      : 99999
Number of days of warning before password expires   : 7
Linux shell                                         : /bin/bash 
Groups                                              : marion, secondary, krq

我需要在一个命令中运行所有内容,所有引号都应该被转义,因为我将在Ansible中运行它。如果有任何其他方式使其在Ansible中运行,我会接受任何建议。

祝你好运, 罗曼

1 个答案:

答案 0 :(得分:0)

您不需要在一个冗长而丑陋的命令中运行所有内容。稍微小心一点,你可以运行任意复杂的代码,虽然我不会对它感到疯狂。 根据您的需要进行调整 -

- name: run a complex shell command
  shell: |
    : careful with comments in here, and best to end lines with semicolons;
    while IFS=: read -r user x uid gid info home shell ;  
    do printf "\n$user\n";
       chage -l $user;
       printf "%-56s: $shell\n" "Linux shell"
       printf "%-56s: " "User Groups"
       grep $user /etc/group | cut -f 1 -d : | paste -s
    done < /etc/passwd > users-list.log
  • 或者更好的是,编写并模拟一个小脚本文件并调用它。

|中的shell: |表示以下数据是单个块标量。窥探new SciPy API for ODE以获取示例和详细说明,但它保留了线条。只需仔细格式化您的缩进。 :)

要添加组,您可以根据here解析该行,但要注意信息字段可能包含也可能没有数据,并且它可能有点任意,可能是嵌入空格。