Ansible控制节点通过SSH连接Windows Server 2019执行win_ping模块报错求助
Let's break down what's happening here and fix this issue step by step:
Root Cause
When you changed Windows' default SSH shell from cmd.exe to PowerShell, Ansible didn't automatically detect this change—it still tried to run cmd-style commands (using && as a statement separator) against PowerShell. Even though modern PowerShell supports &&, the way Ansible formatted the command triggered a parsing error, hence the InvalidEndOfLine message you saw.
Fixes to Try
1. Explicitly Configure Shell Type in Ansible Inventory
This is the most reliable long-term fix. You need to tell Ansible that your Windows host uses PowerShell as its shell, so it generates compatible commands.
Edit your Ansible inventory file (e.g., hosts or inventory.yml):
- For INI format:
[windows-servers] windowsTest_host1 ansible_host=YOUR_WINDOWS_IP ansible_user=YOUR_WINDOWS_USER ansible_password=YOUR_WINDOWS_PASS ansible_shell_type=powershell ansible_shell='powershell.exe -NoProfile -NonInteractive' - For YAML format:
windows-servers: hosts: windowsTest_host1: ansible_host: YOUR_WINDOWS_IP ansible_user: YOUR_WINDOWS_USER ansible_password: YOUR_WINDOWS_PASS ansible_shell_type: powershell ansible_shell: powershell.exe -NoProfile -NonInteractive
After saving the inventory, re-run your win_ping command:
ansible windows-servers -m win_ping
2. Quick Temporary Fix (Command Line Override)
If you want to test without modifying your inventory, pass the shell type as an extra variable:
ansible windows-servers -m win_ping -e "ansible_shell_type=powershell"
3. Should You Set PowerShell as Windows' Default SSH Shell?
It's not strictly required for Ansible management—here's the breakdown:
- Pros: PowerShell offers better integration with Windows-native tools and more flexibility for ad-hoc commands.
- Cons: Changing the default shell might break other scripts or tools that expect
cmd.exeas the default SSH shell.
If you do keep PowerShell as the default, just make sure to always set ansible_shell_type=powershell in your Ansible configuration/inventory. This ensures Ansible generates commands aligned with PowerShell's syntax.
Additional Checks
- Verify your Windows Server 2019 PowerShell version: Run
$PSVersionTable.PSVersionin PowerShell. PowerShell 5.1 (the default on Server 2019) does support&&, but the error you encountered was caused by Ansible passing a cmd-style command to PowerShell. - Confirm OpenSSH's default shell setting: On Windows, run
Get-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell. It should point to PowerShell's executable if you made that change.
内容的提问来源于stack exchange,提问作者anonymthe

