我已经下载了Joakim Svendsen的SSH-Sessions,它使用了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。
我该如何解决这些问题?我应该如何硬编码密码?