Excute Shell Script remotely to Azure Linux VM - powershell

i'am trying to excute a shell script to an azure linux virtual machine using powershell
Why I'm i using powershell? :
The virtual machine has a Copied VHD from storage account which means it doesn't have Azure VM agent
so i can't use :
azure vm extentions
azure vm Runs
i tried also using an automation runbook with the ssh module and got those errors :
Exception calling "Connect" with "0" argument(s): "Server HMAC algorithm not found" At C:\Modules\User\SSH\SSH.psm1:68 char:5 + $SSHConnection.Connect() + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
and
Exception calling "RunCommand" with "1" argument(s): "Client not connected." At C:\Modules\User\SSH\SSH.psm1:69 char:5 + $ResultObject = $SSHConnection.RunCommand($ScriptBlock.ToString() ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
which is based on my understanding caused by the vm that is missing KexAlgorithms to describe which methods are supported by the SSH daemon
What i'm trying to do now is to ssh into the vm and excute the command using powershell
here is what i got now (a Powershell scripot to ssh into the vm and excute a command):
$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
im getting this error :
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
i looked in the internet but couldn't find anything.
apparently the ssh invoke command can't find a session with the index $SessionID
but i don't know where exactly is the problem
hope someone can guide me to the right direction.

Updating Posh-SSH worked for me with this code :
to install Posh-SSH :
Install-Module -Name Posh-SSH -RequiredVersion 2.1
The Script:
$Command = "fetch $scripturl; sh script.sh"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$ComputerName = Get-AzPublicIpAddress -ResourceGroupName $RG -Name $IPName | Select-Object -ExpandProperty ipAddress
echo 'ip is : '
echo $ComputerName
echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -AcceptKey -Credential $Credentials
echo 'Exucuting...'
$Query = (Invoke-SshCommand -SSHSession $SessionID -Command $Command).Output
echo $Query
Remove-SSHSession -Name $SessionID | Out-Null

Related

I want to store encrypted credentials and use them to open a powershell instance and run a script that makes a change to a field in AD

Below is my code, I've used the same process for connecting to sftp securely. I'm getting the error at the bottom of my post. Not sure if I'm missing a step in the creation of the key and password. Thanks.
#Set the credentials
$Password = Get-Content "c:\password.txt" |
ConvertTo-SecureString -Key (Get-Content "c:\aes.key")
$Credential = New-Object System.Management.Automation.PSCredential ('serviceaccount', $Password)
# Start a new instance of Windows PowerShell using the credentials
# stored in $Credential and run the script in $scriptblock
$powershellPath = "$env:windir\system32\windowspowershell\v1.0\powershell.exe"
$process = Start-Process $powershellPath -Credential $Credential -NoNewWindow `
-ArgumentList ("-ExecutionPolicy Bypass -noninteractive -noprofile " + $scriptBlock) -PassThru
# Script to execute in the new PowerShell instance
$scriptBlock = {
Import-Module ActiveDirectory
Get-ADUser ecarlsson | Set-ADUser -Manager bbob
Read-Host
}
I tried the code above and go the password error below.
Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
At\filepath \\fV3.ps1:7 char:12
+ $process = Start-Process $powershellPath -Credential $Credential -NoN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

Powershell to change RDWEB certificates remotely

About to give up on this and connect locally to each system and run the commands but thought it wise to ask the smart people first.
With my credentials locally this works:
Set-Variable -Name "CBROKE" -Value "vmname01.amgsvcs.net"
Set-Variable -Name "CERTPASS" -Value "wHQTD3w6s"
Set-Variable -Name "CERTPATH" -Value "N:\CERTS\vmname01.domain.com.pfx"
Import-Module RemoteDesktop
$Password = ConvertTo-SecureString -String $CERTPASS -AsPlainText -Force
Set-RDCertificate -Role RDWebAccess -ImportPath $CERTPATH -Password $Password -ConnectionBroker $CBROKE -Force
Set-RDCertificate -Role RDPublishing -ImportPath $CERTPATH -Password $Password -ConnectionBroker $CBROKE -Force
Set-RDCertificate -Role RDRedirector -ImportPath $CERTPATH -Password $Password -ConnectionBroker $CBROKE -Force
Set-RDCertificate -Role RDGateway -ImportPath $CERTPATH -Password $Password -ConnectionBroker $CBROKE -Force
If I try to do this remotely with my same domain admin account using
Enter-PSSession -ComputerName vmname01
I get this in response to each Set-RDCertificate:
Get-RDServer : The RD Connection Broker server is not available. Verify that you can connect to the RD Connection
Broker server.
At C:\windows\system32\WindowsPowerShell\v1.0\Modules\RemoteDesktop\Certificate.psm1:309 char:22
+ ... webaccess = Get-RDServer -ConnectionBroker $ConnectionBroker -Role #( ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-RDServer
Set-RDCertificate : Deployment does not contain an RD Web Access server.
At line:1 char:1
+ Set-RDCertificate -Role RDWebAccess -ImportPath $CERTPATH -Password $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Set-RDCertificate
I have used the checks from this page https://stackoverflow.com/questions/65022178/run-invoke-command-in-remote-computer-as-administrator and they all return true that the remote console is elevated.
I realized that these commands don't have to be run locally, they are in effect domain/network type commands and can be run from any machine.

You cannot call a method on a null-valued expression in PowerShell using another credentials

Well, i'm trying to execute a script with another credentials and i got the next error:
You cannot call a method on a null-valued expression.
At C:\Automation\SoftwareInstallation\runas_test\whoami_test.ps1:10 char:1
+ Write-Host $result.StandardOutput.ReadToEnd()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
This is my code:
$username = 'idb\frida_automation_scc'
$pass = Get-Content -Path C:\Automation\SoftwareInstallation\runas_test\settings.txt -Raw
$password = ConvertTo-SecureString $pass -AsPlainText -Force
$MyCredential=New-Object -TypeName PSCredential -ArgumentList $username, $password
$result=Start-Process -NoNewWindow powershell.exe -ArgumentList "-file C:\Automation\SoftwareInstallation\runas_test\whoami_test2.ps1" -Credential $MyCredential -PassThru -RedirectStandardOutput test1.txt
Write-Host $result.StandardOutput.ReadToEnd()
And this is the another command:
$result= whoami
Write-Host $result
return $result
I donĀ“t know why this error happens if the command are well written and the script brought back the value in a .txt file.

Remove-ItemProperty does not support credentials

I tried to remove registry object using admin credentials by powershell
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User,$pass
Invoke-Command -ScriptBlock {Remove-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\office\16.0\outlook\security" -Name "clearsign" -Credential $Credential}
But i got en error below:
The provider does not support the use of credentials. Perform the operation again without specifying credentials.
At line:1 char:1
+ Remove-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\office\1 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported
Based on what microsoft documentation says i have to do use -credentials with Invoke command since it is not supprted , but its still not working
any suggestion how i suppose to do it ?

System Center Configuration Manager - PowerShell Remoting

I have a primary SCCM server - "ABC"
Later I installed SCCM console and PowerShell Module on one more machine - "XYZ"
I am running below script from server - "OPQ" and trying to remote "XYZ" (on which i installed SCCM Console Recently)
Script ::
$Session = New-PSSession -ComputerName "XYZ" -Authentication Kerberos -Credential $Cred -ConfigurationName Microsoft.PowerShell32
Invoke-Command -Session $Session -ScriptBlock {
Import-module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
Set-Location PS1:\
}
ERROR ::
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OpenError: (PS1:PSDriveInfo) [Import-Module], UnauthorizedAccessException
+ FullyQualifiedErrorId : Drive,Microsoft.PowerShell.Commands.ImportModuleCommand
+ PSComputerName : XYZ
Cannot find drive. A drive with the name '' does not exist.
+ CategoryInfo : ObjectNotFound: (PS1:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
+ PSComputerName : XYZ
Well it appears you have a permissions issue. Here is how I executed a remote command in my SCCM environment, via my PSS:
$device = Invoke-Command -Session $sess -ScriptBlock {
Import-Module (Join-Path (Split-Path $env:SMS_ADMIN_UI_PATH)
ConfigurationManager.psd1)
Push-Location -Path ((Get-WmiObject -Namespace "root\SMS" -Class
"SMS_ProviderLocation" | Select-Object -ExpandProperty SiteCode) + ":")
Get-CMDevice -Name $env:COMPUTERNAME
Pop-Location
}
$device
RunspaceId : cbc7e008-d92c-4ba3-94a3-b75f8005be98
SmsProviderObjectPath : SMS_CM_RES_COLL_SMS00001.ResourceID=16777221
AADDeviceID : 00000000-0000-0000-0000-000000000000
AADTenantID : 00000000-0000-0000-0000-000000000000
ActivationLockBypassState :
ActivationLockState :
ADLastLogonTime : 3/31/2020 11:23:38 PM
ADSiteName : XXXX-XX
...
Note that if you're not remoting to your PSS, you will need to specify your PSS in the Get-WmiObject command, e.g.:
(Get-WmiObject -ComputerName [YOUR PSS] -Namespace "root\SMS" -Class "SMS_ProviderLocation" | Select-Object -ExpandProperty SiteCode) + ":"
I was able to resolve this issue by saving the credentials on the XYZ server and then calling them under my INvoke-Command.
Like This :
$Session = New-PSSession -ComputerName "XYZ"
Invoke-Command -Session $Session -ScriptBlock {
$password = Get-Content -Path D:\Creds\creds.txt | ConvertTo-SecureString
$Cred = New-Object System.Management.Automation.PSCredential ("domain\UserId", $password)
Then the rest of the code. ... .. . . .
}