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

使用PowerShell远程执行脚本到无Azure VM Agent的Azure Linux VM遇参数错误

问题与解决方案

问题背景与现状

  • 需通过PowerShell向无Azure VM Agent的Azure Linux虚拟机执行Shell脚本(该VM由存储账户VHD复制创建)
  • 无法使用Azure VM扩展、Azure VM Runs功能
  • 此前尝试自动化Runbook的SSH模块连接时,因VM缺少KexAlgorithms,出现Server HMAC algorithm not found和Client not connected错误
  • 当前编写的PowerShell SSH脚本执行时,触发Invoke-SshCommand参数错误:找不到Index参数

原脚本

$Password = "pwd"
$User = "pwd"
$ComputerName = "ip adress"
$Command = "touch tst.txt"

$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)

echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -Credential $Credentials #Connect Over SSH
echo 'Executing...'
$output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Output
Remove-SSHSession -Name $SessionID | Out-Null

错误信息

Invoke-SshCommand : A parameter cannot be found that matches parameter name 'Index'.
At C:\Users\octoadmin\Desktop\sign in.ps1:11 char:30
+ $output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Out ...
+                              ~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-SshCommand], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Invoke-SshCommand

解决步骤

1. 修复Invoke-SSHCommand参数错误

New-SSHSession返回的是SSH会话对象,而非单纯的ID值。Invoke-SSHCommand没有-Index参数,正确参数为-Session,需传入会话对象。

2. 解决KexAlgorithms缺失导致的SSH握手失败

在建立会话时,手动指定兼容的Kex算法、MAC算法,解决之前的握手错误。

修正后的完整脚本

$Password = "your-actual-password"
$User = "your-username"
$ComputerName = "vm-public-ip"
$Command = "touch tst.txt"

# 转换为安全凭据
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)

# 定义兼容的SSH算法,解决KexAlgorithms缺失问题
$sshParams = @{
    ComputerName = $ComputerName
    Credential = $Credentials
    KexAlgorithms = "diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha1"
    MacAlgorithms = "hmac-sha1,hmac-md5"
}

Write-Host 'Logging in via SSH...'
$sshSession = New-SSHSession @sshParams

Write-Host 'Executing command...'
# 使用-Session参数传入会话对象,而非-Index
$output = (Invoke-SSHCommand -Session $sshSession -Command $Command).Output

# 清理会话
Remove-SSHSession -Session $sshSession | Out-Null

# 输出结果
Write-Host "Command output:`n$output"

关键修改说明

  • 移除错误的-Index参数,改用-Session传入New-SSHSession返回的会话对象
  • 添加KexAlgorithms和MacAlgorithms参数,指定VM支持的旧版算法,解决SSH握手失败问题
  • 使用哈希表@sshParams整理参数,提升可读性
  • 替换占位符(密码、用户名、IP)为实际值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:48:15