Windows-取得本機帳號清單
在 Windows 要取得本機帳號清單,Ansible 沒有這樣的模組,只能透過 win_shell 或 win_powershell 來達成。
PowerShell 要使用的指令是 Get-LocalUser
。
輸出的結果是這樣子的
PS C:\Users\Administrator> Get-LocalUser
Name Enabled Description
---- ------- -----------
Administrator True Built-in account for administering the computer/domain
DefaultAccount False A user account managed by the system.
Guest False Built-in account for guest access to the computer/domain
WDAGUtilityAccount False A user account managed and used by the system for Windows Defender Application Guard scen...
winrm01 True
若需要其他欄位,可以用 Select
PS C:\Users\Administrator> Get-LocalUser | Select Name, PasswordExpires
Name PasswordExpires
---- ---------------
Administrator
DefaultAccount
Guest
WDAGUtilityAccount 4/22/2022 9:07:12 AM
winrm01
在 Playbook 裡可以這樣寫
- name: Get-LocalUser
ansible.windows.win_shell: Get-LocalUser
register: shell_output
- name: Display local users
debug:
var: shell_output.stdout
- name: Get-LocalUser | Select Name, PasswordExpires
ansible.windows.win_shell: Get-LocalUser
register: shell_output
- name: Display local users with customized columns
debug:
var: shell_output.stdout
如果在 Ansible playbook 裏面需要做一些處理或判斷的話,文字的輸出其實不是很方便。這時候可以透過 PowerShell 的 ConvertTo-Json 跟 Ansible 的 from_json 將輸出轉為可處理的變數。
- name: Get-LocalUser
ansible.windows.win_shell: Get-LocalUser | ConvertTo-Json
register: shell_output
- name: Convert to Variable
set_fact:
user_list: "{{ shell_output.stdout | from_json }}"
- name: Display local users
debug:
var: user_list
看到這邊,相信你已經知道怎麼去作 Windows 的帳號清查了。