Azure Pipelines通过SSH无法在Windows服务器执行命令排查求助
问题排查与解决方案
核心问题分析
从日志可见,执行cd命令后当前目录未切换,根源是Windows OpenSSH服务器默认使用cmd.exe作为shell,SSH@0任务的多条命令会在独立的cmd进程中执行,导致目录切换状态无法延续到后续命令。同时命令写法混合了cmd与PowerShell语法,进一步加剧了兼容性问题。
排查与修复步骤
1. 将目标服务器的OpenSSH默认shell切换为PowerShell
Windows OpenSSH默认shell是cmd.exe,改为PowerShell可确保所有命令在同一会话中执行,目录切换等状态会被保留:
- 登录目标Windows服务器,以管理员权限打开PowerShell
- 执行命令查看当前默认shell:
Get-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell - 若结果不是PowerShell路径,执行以下命令修改:
Set-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" - 重启OpenSSH服务:
Restart-Service sshd
2. 修改SSH@0任务的命令写法
改用PowerShell语法,优先使用绝对路径规避当前目录依赖,确保命令执行逻辑连贯:
- task: SSH@0 displayName: 'Setting up APP1' inputs: sshEndpoint: 'SSH - GTP325 - APP1' runOptions: 'commands' commands: | Write-Host 'Changing permissions to APP1.zip file...' icacls "C:\Users\Administrator\Desktop\APP1\" /reset /t /c /q Write-Host "Current directory" Get-Location Write-Host "Changing Directory.." Set-Location "C:\Users\Administrator\Desktop\APP1" Write-Host "Display current directory" Get-Location Get-ChildItem Write-Host 'Decompressing APP1.zip files...' tar -xf "C:\Users\Administrator\Desktop\APP1\APP1.zip" Write-Host 'running scripts for setup...' & "C:\Users\Administrator\Desktop\APP1\APP1\APP1-file-check.ps1" readyTimeout: '20000'
说明:
- 用
Write-Host替代echo,贴合PowerShell语法规范 - 所有路径使用绝对路径,彻底消除当前目录依赖问题
- 用
Set-Location替代cd(PowerShell中cd是别名,显式写法更清晰) - 用
&调用PowerShell脚本,确保脚本正确执行
3. 备选方案:使用独立脚本文件执行
若上述方法仍存在问题,可将所有操作封装为PowerShell脚本,通过WindowsMachineFileCopy@2传到目标服务器后执行:
- 在Pipeline中添加文件复制任务,将
setup-app1.ps1传到服务器的C:\Users\Administrator\Desktop\目录 - 修改SSH@0任务:
- task: SSH@0 displayName: 'Setting up APP1' inputs: sshEndpoint: 'SSH - GTP325 - APP1' runOptions: 'commands' commands: | powershell -ExecutionPolicy Bypass -File "C:\Users\Administrator\Desktop\setup-app1.ps1" readyTimeout: '20000'
4. 验证路径正确性
在命令中添加目录存在性检查,避免因路径拼写错误导致失败:
$targetDir = "C:\Users\Administrator\Desktop\APP1" if (!(Test-Path $targetDir)) { Write-Error "Target directory $targetDir does not exist!" exit 1 }
内容的提问来源于stack exchange,提问作者Chris Tsag
相关产品推荐
相关产品推荐

