SSH Check Connection - powershell

I would like to check if machines have SSH installed.
So, I have this script:
I want the script to try to connect on machines and make a .txt 'log' like this:
10.10.10.1 - Connection refused (machines not have SSH or is down)
10.10.10.2 - Connection OK
...
$db = Get-Content -Path ".\hosts.txt"
$User = "user"
$Password = "pass"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $db -Credential $Credentials -AcceptKey:$true
In hosts.txt I have hostip for machines
eg:
10.10.10.1
10.10.10.2
10.10.10.3
...

Any ideea ?
$LogFile = ".\LogMachines.txt"
function LogMessage
{
param([string]$Message)
((Get-Date).ToString() + " - " + $Message) >> $LogFile;
}
$db = Get-Content -Path ".\hosts.txt"
$User = "user"
$Password = "pass"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $db -Credential $Credentials -AcceptKey:$true
LogMessage -Message "$db connected - OK";
LogMessage -Message "$db failed to connect - X";

Related

Powershell: Using specific credentials to execute a command

Dears,
In my Powershell script, I would like to use a specific credential on a remote computer. This login exists on the remote computer and is local.
Hence, my code looks like this:
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$Vault = New-Object Windows.Security.Credentials.PasswordVault
$RESOURCE = "Resource"
$USERNAME = "MyLogin"
try {
$credentials = $Vault.Retrieve($RESOURCE,$USERNAME)
$pwd = $credentials.Password | ConvertTo-SecureString -Key (1..16)
}
catch {
$pwd = Read-Host "please enter your password:" -AsSecureString
$Encrypted = ConvertFrom-SecureString -SecureString $pwd -Key (1..16)
$credentials = new-object -Type Windows.Security.Credentials.PasswordCredential -ArgumentList $RESOURCE,"REMOTE_COMPUTER\"+$USERNAME,$Encrypted
$Vault.Add($credentials)
}
$cred = New-Object System.Management.Automation.PsCredential($USERNAME,$pwd)
$ComputerMemory = Get-WmiObject -ComputerName "REMOTE_COMPUTER" -Class win32_operatingsystem -ErrorAction Stop -Credential $cred
$Memory = ([math]::round(((($ComputerMemory.TotalVisibleMemorySize - $ComputerMemory.FreePhysicalMemory)*100)/ $ComputerMemory.TotalVisibleMemorySize), 2))
echo $Memory
Problem of course is when executing GetWmiObject, I got an Access denied error...
Is there something wrong with this code?
Thanks in advance for your feedback,
Kind regards,

PS credential retry

I have this script
$db = import-csv -Path ".\testdb.csv"
$inputID = Read-Host -Prompt "ID"
$entry = $db -match $inputID
Write-Host "IP:" $entry.IP
$User = "user"
$Password = "pass"
$User2 = "user2"
$Password2 = "pass2"
$Command = "C:\test.exe"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$secpasswd2 = ConvertTo-SecureString $Password2 -AsPlainText -Force
$Credentials2 = New-Object System.Management.Automation.PSCredential($User2, $secpasswd2)
Get-SSHTrustedHost | Remove-SSHTrustedHost
try {
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials -AcceptKey:$true
}
catch {
$SessionID = New-SSHSession -ComputerName $entry.IP -Credential $Credentials2 -AcceptKey:$true
}
Is any chance to try connect with 2 different credentials ; if one fail try to other?
So.. first time try user and password ; second time try user2 and password2
Thank you. :)

Find the exact matched string from the variable

In the below code, $Result variable has the following information. I need to iterate below each line in $Result variable and get the <APPPOOL NAME> that is, "DefaultAppPool","Classic .NET AppPool" & ".NET v2.0 Classic" as an input to the second Invoke-Command saved in $Result2. Please advise how this can be accomplished.
$Result output:
APPPOOL "DefaultAppPool" (MgdVersion:v4.0,MgdMode:Integrated,state:Started)
APPPOOL "Classic .NET AppPool" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
APPPOOL ".NET v2.0 Classic" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
$Username = '<username>'
$Password = '<Password>'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $pass
$input_file_path = "servers.txt"
$output_path = "result.txt"
foreach ($server in Get-Content $input_file_path) {
$Result = Invoke-Command -ComputerName $server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools
}
$Result | Add-Content $output_path
$Result2 = Invoke-Command -ComputerName #server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools <APPPOOL NAME> /text:processmodel.username
}
}

Permission denied error while creating file in remote system by Azure powershell

I have written below code to create file in remote system by domain credentials.
When i execute this code I get permission denied error.
Code:
$username = "domain\username"
$password = "Welcome1234$"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
Invoke-Command -Credential $cred -Computer VM1{
New-Item \\VM2\sapmnt\SID\SYS\profile\test.txt -ItemType file
}
error:
Access to the path '\\VM2\sapmnt\SID\SYS\profile\test.txt' is denied.
+ CategoryInfo : PermissionDenied: (\\VM2\s...rofile\test.txt:String) [New-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
Can you use that account to access that path \\VM2\sapmnt\SID\SYS\profile? Do you have permission to read or write?
I had test in my lab, it works for me.
Grant permission (Read/Write)to that account:
Here is the script:
$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'http://13.73.23.129:5985' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {new-item \\jasonvm\profile\jasontest3.txt}
Update:
changing the ip-address to HOSTNAME resolve this issue:
$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'VM2hostname:5985'; -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {new-item \\jasonvm\profile\jasontest3.txt}

Issues passing credentials to a function Azure Powershell

Hi all I'm trying to pass server login credentials to my 'createSQLServer function but keep hitting the error 'Cannot process argument transformation on parameter 'creds'.userName'' I've tried a lot of different, even tried with a 'param block' but stull stuck. A push in the right direction would be appreciated, cheers.
###### SQL SERVER LOGIN CREDENTIALS
$userName = "aaron"
$password = "Password_1234"
$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $securePassword
### SQL server names with resource group name appeneded
$server1 = "sqlserver1" + $resGroup
$serVerion = "12.0"
function createSQLserver ([string]$server1,[string]$server2, [string]$server3, [System.Management.Automation.PSCredential]$creds,[string]$server1Location, [string]$server2Location, [string]$server3Location, [string]$resGroup, [string]$serVerion, [string]$userName, [string]$password, [SecureString]$securePassword)
{
#Create server 1(Server A)
<#check to see if server exists - It exists, $continue is created and passed to
if statement to append two random characters to name#>
Write-Host "Creating First SQL Server"
$sqlServer = New-AzureRmSqlServer -ServerName $server1 -SqlAdministratorCredentials $creds -Location $server1Location -ResourceGroupName $resGroup -ServerVersion $serVerion -ErrorVariable continue -ErrorAction SilentlyContinue
if ($continue)
{
do {
$server1 = $server1 + (rand)
$sqlServer = New-AzureRmSqlServer -ServerName $server1 `
-SqlAdministratorCredentials $creds -Location $server1Location `
-ResourceGroupName $resGroup -ServerVersion "12.0" -ErrorVariable continue -ErrorAction SilentlyContinue
}
until(!$continue)
Write-Host 'exists creating new' $server1 'Created'
}else{
Write-Host $server1 ' Created'
}
Start-Sleep -s 2
}
createSQLserver $server1 $username $password $securePassword $creds $server1Location $resGroup $serVerion
You need to use your named parameters!
Here's a snippet of your first few parameters:
...
[string]$server1
,
[string]$server2
,
[string]$server3
,
[System.Management.Automation.PSCredential]$creds
...
And then the ones you're passing in to the function call
createSQLserver $server1 $username $password $securePassword ...
So because you're not using the names of your parameters, they are using their relative ordinal position i.e.
param | value
---------+----------------
$server1 | $server1
$server2 | $username
$server3 | $password
$creds | $securePassword
So what have we learned?
Always use named parameters!
createSQLserver -server1 $server1 -username $username -password $password -securePassword $securePassword
That should sort you out :-)