在 Windows PowerShell 7 .ps1 脚本中通过 SSH 远程运行 Shell/Linux 命令

在 Windows PowerShell 7 .ps1 脚本中通过 SSH 远程运行 Shell/Linux 命令

我试图找到在.ps1PowerShell 脚本中通过 SSH 在 Linux 服务器上运行命令的最简单、最直接的方法,在 Windows 10 上运行 PowerShell 7。

我有一个通过 SCP/PuTTY 上传 zip 文件的过程,完成后,我的脚本通过 SSH 进入服务器,从那里我需要运行几个 Linux 命令来解压缩文件并运行 Docker 构建/编写。

# param1: destination server ip
$ip=$args[0]
# param2: path on the server
$path=$args[1]
# param3: username
$un=$args[2]
# param4: password # TODO: figure out how to hide
$pw=$args[3]
# source path

if (!$pw) { throw "Password can't be null." }

$src = "../"
# construct archival name
$DateTime = (Get-Date -Format "yyyyMMddHHmmss")
$zip = "..\deploy_archive\deploy-$DateTime.zip"
# Create archive
mkdir -Force ..\deploy_archive
# exclusion rules. 
$files = Get-ChildItem -Path $src -Exclude @("node_modules", "deploy_archive")
# Compress
Compress-Archive -Path $files -DestinationPath $zip -CompressionLevel Fastest
# Report status
Write-Output "`nZipped archive: $($zip)"
# PuTTY SCP file transfer command
$Cmd = ("pscp -l {0} -pw {1} -batch {2} {3}:{4}" -f $un,$pw,$zip,$ip,$path)
Write-Output "cmd: $Cmd"
Invoke-Expression "& $( $Cmd )"
# Report success
Write-Output ("`nUploaded to  {0}:{1}" -f $ip,$path)
# Connect via SSH
ssh ("{0}@{1}" -f $un,$ip)

# ...NOW DO STUFF ON THE REMOTE SERVER
# ...like unzip and run Docker build

我可以添加一个老式的 ssh 命令,例如:

ssh [email protected]

然后它要求我输入密码并成功连接,但此后添加的脚本直到我退出 SSH 会话后才会执行。

如果我使用:

# SSH-Sessions -ComputerName $ip -Username $un -Password $pw

我得到:

> [some.ip.add.ress] The background process reported an error with the
> following message: The SSH client session has ended with error
> message: subsystem request failed on channel 0.

uname -a在服务器上给我:

Linux azrahznval0002 3.10.0-1160.15.2.el7.x86_64 #1 SMP Thu Jan 21 16:15:07 EST 2021 x86_64 x86_64 x86_64 GNU/Linux

答案1

ssh [email protected] @'

    # My Bash commands here.
    # Alternatively, I can invoke PowerShell or Python if installed.

'@

或者,针对您的特定用例:

ssh ("{0}@{1}" -f $un, $ip) @'

    # My Bash commands here.
    # Alternatively, I can invoke PowerShell or Python if installed.

'@

答案2

我找到了解决方案和部分答案StackOverflow 上提出了相关问题。我没想到会在那里找到这个...但是您可以使用命令内联运行命令ssh,这是直观的,而且很明显,考虑到您在大多数情况下想要如何做这样的事情。

我怎么会是第一个在这里发布解决方案的人呢,哈哈?每个人都应该知道这一点。

仍然想知道为什么我的 SSH-Sessions 命令不起作用,但这可能是服务器上的问题......

相关内容