You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法通过PowerShell的sshArgs在远程Linux主机执行SSH命令

GitHub Actions PowerShell脚本字符串终止符错误排查与修复

核心错误原因

脚本中icacls命令行的引号配对错误,导致整个脚本的字符串解析逻辑混乱——虽然错误提示指向Write-Output "$sshArgs",但实际语法问题出在更早的代码行:

原错误代码行:

icacls "C:\id_rsa" /inheritance:r /grant $env:USERNAME`:R"

该行末尾多了一个多余的双引号,且权限参数未正确用引号包裹,导致PowerShell解析时认为字符串未终止。

修复步骤

  1. 修正icacls命令的引号语法
    将上述行改为:
icacls "C:\id_rsa" /inheritance:r /grant "$env:USERNAME:R"

用双引号完整包裹$env:USERNAME:R参数,同时移除末尾多余的引号,确保语法配对正确。

  1. 优化数组输出写法(可选)
    Write-Output "$sshArgs"会将数组元素用空格拼接成字符串,若要查看数组的原始结构,建议改为:
Write-Output $sshArgs
# 或者查看结构化输出
ConvertTo-Json $sshArgs
  1. 安全执行ssh命令(替代注释的代码)
    原注释中用Invoke-Expression拼接命令的方式存在安全风险,推荐使用PowerShell的数组splatting语法直接调用ssh:
& ssh.exe @sshArgs

这种方式会自动将数组$sshArgs中的每个元素作为独立参数传递给ssh.exe,避免字符串拼接带来的转义问题。

完整修复后的PowerShell脚本片段

$remoteHosts = "80.240.24.192,80.240.24.193".Split(",")
$user="root"
Set-Content -Path "C:\id_rsa" -Value '{{ secrets.myunixkey }}'
icacls "C:\id_rsa" /inheritance:r /grant "$env:USERNAME:R"

foreach ($eachHost in $remoteHosts) {
  echo $eachHost

  $sshArgs = @(
    "-o", "StrictHostKeyChecking=no",
    "-o", "UserKnownHostsFile=/dev/null",
    "-i", "C:\id_rsa",
    "$user@$eachHost",
    "hostname"
  )

  Write-Output $sshArgs
  & ssh.exe @sshArgs
}

内容的提问来源于stack exchange,提问作者Ashar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 00:54:52