我已下载使用SSH-Sessions by Joakim Svendsen的SSH.NET并在Jenkins Windows服务器中安装了PowerShell模块
在Jenkins中,我有以下PowerShell脚本:
Import-Module SSH-Sessions
$lastExitCode = 0
$devApp1 = "10.0.0.1"
$devApp2 = "10.0.0.2"
Write-Output "Deployment started in $devApp1......"
New-SshSession -ComputerName $devApp1 -Username test -Password test@123
$return = Invoke-SshCommand -ComputerName $devApp1 -Command "cd /NFS_DATA/autodeploy_scripts && echo test@123 | ./autodeploy.sh"
$return | Get-Member
if ($lastExitCode -ne 0)
{
Write-Output $lastExitCode
exit 1;
}
else
{
Write-Output $lastExitCode
exit 0;
}
shell脚本包含:
#!/bin/bash
file="/NFS_DATA/autodeploy_scripts/test.log"
if [ -f "$file" ]
then
echo "$file found."
exit 0;
else
echo "$file not found."
exit 1;
fi
问题是找不到文件时Jenkins作业不会失败。 Jenkins的输出是:
> Deployment started in 10.0.0.1...... Successfully connected to > 10.0.0.01 > 10.0.0.01 had an error: Finished: SUCCESS
在提出一些建议后,我使用Posh-SSH编写了以下PowerShell脚本。我也遇到了这个错误,虽然它有所不同。
#Import-Module SSH-Sessions
Import-Module Posh-SSH
# Setup static variables
$devApp1="10.0.0.1"
$devApp2="10.0.0.2"
$username = "test"
$password = "test@123"
$command = "cd /NFS_DATA/autodeploy_scripts && echo Hybris@123 | ./autodeploy.sh"
Write-Output "Deployment started in $devApp1..."
# Setup PSCredentials
$secPasswd = ConvertTo-SecureString $password -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential ($username, $secPasswd)
echo $credentials
# Estalbish new SSH session automatically accepting new SSH keys
$session = New-SSHSession -Computername $devApp1 -Credential $credentials -Acceptkey:$true
# Invoke command to be run on/in the SSH session
$output = Invoke-SSHCommand -SSHSession $session -Command $command
Write-Output "Returned Output from the Command: "
Write-Output $output.Output
Write-Output "Last Exit Status: "
Write-Output $output.ExitStatus
将错误消息显示为:
相同的代码在我的本地笔记本电脑中工作,但在Jenkins服务器中失败。
我认为在Jenkins服务器中,由于Windows安全限制,不会存储从PSCredential检索到的$secpasswd
。这导致仅将用户名提供给POSH。
我该如何修复这些问题?我该如何硬编码密码?
答案 0 :(得分:3)
由于您从未说明这些命令的来源,我将假设您正在使用Posh-SSH。通过查看关于它的this article,解决方案可能是:
$dev_app1="10.00.00.01"
$dev_app2="10.00.00.02"
echo "Deployment started in $dev_app1......"
Import-Module SSH-Sessions
New-SshSession -ComputerName $dev_app1 -Username test -Password test@123
$result = Invoke-SshCommand -ComputerName $dev_app1 -Command "cd /NFS_DATA/autodeploy_scripts && echo test@123 | ./autodeploy.sh"
Write-Output "Returned Output from the Command: "
Write-Output $result.Output
Write-Output "Last Exit Status: "
Write-Output $result.ExitStatus
if($result.ExitStatus -ne 0){
exit $result.ExitStatus;
}
if
可以省略,只是出于演示目的。之后所有退出状态都为0。
使用Get-Member
获取有关$result
的信息(如果这不起作用)的正确方法是:$result | Get-Member
。这将输出任何类型的对象$result
的一般属性。
因为看起来你是running this。您需要运行以下命令来获取对象:
$result = $SshSessions."$dev_app1".RunCommand('cd /NFS_DATA/autodeploy_scripts && echo test@123 | ./autodeploy.sh')
您要使用此而不是Invoke-SshCommand
,并且需要将$result.Output
更改为$result.Result
。