I have downloaded SSH-Sessions by Joakim Svendsen which uses SSH.NET and installed the PowerShell module in the Jenkins Windows server
In Jenkins, I have the following PowerShell script:
Import-Module SSH-Sessions
$lastExitCode = 0
$devApp1 = "10.0.1.109"
$devApp2 = "10.0.1.110"
Write-Output "Deployment started in $devApp1......"
New-SshSession -ComputerName $devApp1 -Username test -Password test#123
The problem is that the Jenkins job doesn't get failed when the connectivity fails. The Jenkins output is:
Unable to connect to 10.0.1.109: Exception calling "Connect" with "0" argumen
t(s): "No connection could be made because the target machine actively refused
it"
Finished: SUCCESS
How can I fix this issue?
Using this documentation, I would do something like this:
New-SshSession -ComputerName $devApp1 -Username test -Password test#123
if (!$SshSessions.$devApp1.Connected) {
throw "Session to $devApp1 is not connected"
}
Or this:
New-SshSession -ComputerName $devApp1 -Username test -Password test#123
$Session = Get-SshSession -ComputerName $devApp1
if (!$Session.Connected) {
throw "Session to $devApp1 is not connected"
}
Obviously, if you've got multiple connections to $devApp1 this code will not work, but the examples in the doc suggest it won't allow you to do that. For whatever reason New-SshSession doesn't support the -PassThru parameter, nor does it seem to return the session, nor does it allow you to specify a variable for the session. Instead the design uses a global variable: $SshSessions. Not the way I'd design it.
You might want to look into Posh-SSH. I don't remember if that is designed better, but I don't remember this kind of issue. It also uses the SSH.Net library. Alternately, WinSCP has a .Net assembly that is very easy to use from PowerShell.
Related
Morning guys,
I'm running into an issue where I have a script that joins a Server to a Domain and restarts, intalls it's roles/features, etc and then restarts it again. I don't have an issue with the first restart:
Restart-Computer -ComputerName $IP -Credential $AdminCred -Wait -For PowerShell
but when I try to do the second restart at the end of the script it get the following error
Restart-Computer : The computer is skipped. Fail to retrieve its LastBootUpTime via the WMI service with the
following error message: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
The following is the original code I tried
Restart-Computer -ComputerName $HostName -Wait -For PowerShell
Without credentials, as I expect Kerberos to work as the account from the laptop has proper permissions
but I also ran it with -Credential and same error. Then I tried changing $HostName to $IP and still no luck.
I can get around the error, by enclosing the Restart-Computer command into an invoke-command session but then I can't "wait for powershell" unless I set an arbitrary sleep timer for a couple minutes.
Any Ideas are appreciated!
I figured it out. I had to add the -WsmanAuthentication param and specify Kerberos. Final code
Restart-Computer -ComputerName $HostName -WsmanAuthentication Kerberos -Wait -For PowerShell
I'm having a bit an issue invoking a command to remotely turn off services via PowerShell. I'm successful when using
(Get-Service -Name tomee -ComputerName servernamefqdn).Stop()
However when using
Invoke-Command -ComputerName servernamefqdn -Credential $creds -ScriptBlock {
(Get-Service -Name tomee).Stop()
}
I get errors
enter-pssession...winrm cannot process
and
The following error occurred while using Kerberos authentication: Cannot find the computer servernamefqdn.
I'm using my own credentials to pass in invoke. I've already ran the quick config for WinRM and added trusted sites for all. I'm not understanding why the first command works but the invoke command doesn't seem to find the server. The goal is the script will remotely stop services using another account. I read 1 other person having this same issue but no real solution for me. Any ideas?
So basically I've been working forever on a PS remote self help script that originally was thought to be simple: Restart the spooler service, clear the queue, and print a test page on the default printer. Getting there however hasn't been so easy, due to security issues. After some hours, I was able to get my local user test account to accept the credentials of my domain administrator. I thought all was well, until I tried to replicate it on a local administrator's account, in which event access was denied. This is sort of important, because the majority of the accounts we will be deploying the script on are local admins. I suspect it may be a UAC issue, but I have no idea what I should do to work around the problem. Here's what I'm working with currently:
$v = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
If ($v = "False")
{
$password = "ElPassword" | ConvertTo-SecureString -asPlainText -Force
$username = "Domainname\Username"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
invoke-command {Stop-Service spooler} -comp $env:ComputerName -cred $credential
Remove-Item C:\Windows\System32\spool\PRINTERS\* -Force
invoke-command {Start-Service spooler} -comp $env:ComputerName -cred $credential
$printer = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"
$PrintTestPage = $printer.PrintTestPage() } Else
{ Stop-Service spooler
$printer = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"
Start-Service spooler
$PrintTestPage = $printer.PrintTestPage() }
The first thing this does is check if the current PS session is being run as admin; seeing as the users don't actually see the PowerShell window or script, and we recently started using the RMM tool, I'm still trying to figure out under what conditions the tool runs PS elevated - the documentation says that it runs with the credentials of the logged in user, but that doesn't seem to be the case, as an hour with their support team told me that the reason the script wasn't doing it's job on any admin accounts was because it wasn't being elevated. Anyways, after the check, it either passes credentials for the commands or it doesn't. This script seems to handle every scenario but that of a local admin account running PS non elevated. In that event, it simply denies me access where the exact same creds give me access on a regular user account. I'm not sure how to even approach this problem, so any help is appreciated.
I've a strange problem that I can't understand. Maybe someone will be able to explain it to me.
I'm trying to automate the installation of an app for SharePoint in a multitenant environment. I run the scripts on a remote machine like this:
$session = New-PSSession -Name "Install App Session" -Authentication Credssp -Credential $InstallAccountCredentials -ComputerName $frontend
$installAppScriptPath = Join-Path $currentScriptPath "\SharePoint\InstallApp.ps1"
$job = Invoke-Command -Session $session -FilePath $installAppScriptPath -ArgumentList $customerUrl, $env:COMPUTERNAME -AsJob
Wait-Job $job
Inside the InstallApp.ps1 I invoke the Import-SPAppPackage command but I get an "Access denied.
You do not have permission to perform this action or access this resource." error. However, if I login to the machine with exactly the same credentials that are used as $InstallAccountCredentials and start the script, everything is working perfectly fine. The account that is used for running this script is an tenant admin account.
Is there something I miss in invoking the command?
PowerShell remote doesn't work for a significant portion of the SharePoint cmdlets. Use the client object model instead - you can invoke those methods from PowerShell as needed.
I ran the below commands on my machine to download data from one server to another server using the invoke command
Enable-PSRemoting -force
Enter-PSSession Server1
invoke-command -computername Server1 -credential:'dom\jack' {c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true}
ERROR is: Failed: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
but when i run the above command on my machine as
c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true
it works as expected.
Is there something i am missing when i execute it remotely....please help me.
thanks
Try this good References:
http://www.ravichaganti.com/blog/?p=1108
http://technet.microsoft.com/en-us/magazine/ff700227.aspx
It might be something to do with the TrustedHosts or Authentication
setting of a client. You can set it like this:WinRM set
winrm/config/client #{TrustedHosts="*"}
Read more about this here:
http://blogs.dirteam.com/blogs/sanderberkouwer/archive/2008/02/23/remotely-managing-your-server-core-using-winrm-and-winrs.aspx
I use
powershell.exe -ExecutionPolicy Unrestricted -WindowStyle Hidden -NoLogo
I use this code:
try
{
Invoke-Command -credential $testCred -computer $ServerName -scriptblock {
param([String]$scriptDeploy, [String]$destino) &"$scriptDeploy" 'parametro1' $destino
$ScriptBlockOutput = $Error
} -ArgumentList $RutaRemotaParaScriptDeInstalacion, "$dirRemotoDestino"
"`r`n`r`nOK para script de despliegue"
exit 0;
}
catch
{
"`r`n`r`nError en script de despliegue"
"`r`nError in " + $_.InvocationInfo.ScriptName + " at line: " + $_.InvocationInfo.ScriptLineNumber + ", offset: " + $_.InvocationInfo.OffsetInLine + ".";
exit -1
}
You need to enable remoting on the remote machine. You also need to make sure the firewall/anti virus does not block the remoting ports. These are port 5985 for http, or port 5986 for https.
If both machines on the same domain it's fairly easy to get working. If the machines are on different domains however then it's more complex. There's a registry setting that needs to be changed on the remote server, and you need to pass credentials. Have a read here for more info. There is of course ssl which can also be enabled, but that's another story.
There is a bug in your script.
You should not be executing Enter-PSSession before the Invoke-Command, because the Invoke-Command itself sets up the PSSession.
Use only this:
Invoke-command -computername Server1 -credential:'dom\jack' {c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true}
... Without the Enter-PSSession