VMware Cloud Community
ganapa2000
Hot Shot
Hot Shot
Jump to solution

get hostname and port details from text file

Hi,

Is there a way to get hostname and port details from one text file instead of executing the script multiple times, I am trying to ssh to linux machines (Posh-SSH)

New-SSHSession -ComputerName mylinux -Port 222 -Credential $credential -AcceptKey

New-SSHSession -ComputerName mylinux1 -Port 223 -Credential $credential -AcceptKey

I tried executing

New-SSHSession -ComputerName mylinux1:223 -Credential $credential -AcceptKey

I am getting the error

New-SSHSession : No such host is known

At line:1 char:1

+ New-SSHSession -ComputerName mylinux1:223 -Credential $credential -AcceptK ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (Renci.SshNet.SshClient:SshClient) [New-SSHSession], SocketException

    + FullyQualifiedErrorId : SSH.NewSshSession

please help

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

The Port is a separate parameter.

To do this based on a CSV file, you could do something like this

# CSV with these columns

#

# HostName,Port,Command

# host1,22,ls

# host2,422,uname

#

# This assumes the same credentials will work on all hosts

$cred = Get-Credential

Import-Csv -Path .\targets.csv -UseCulture | %{

    $ssh = New-SSHSession -ComputerName $_.HostName -Port $_.Port -Credential $cred -AcceptKey

    Invoke-SSHCommand -SSHSession $ssh -Command $_.Command

    Remove-SSHSession -SSHSession $ssh

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

Reply
0 Kudos
4 Replies
LucD
Leadership
Leadership
Jump to solution

The Port is a separate parameter.

To do this based on a CSV file, you could do something like this

# CSV with these columns

#

# HostName,Port,Command

# host1,22,ls

# host2,422,uname

#

# This assumes the same credentials will work on all hosts

$cred = Get-Credential

Import-Csv -Path .\targets.csv -UseCulture | %{

    $ssh = New-SSHSession -ComputerName $_.HostName -Port $_.Port -Credential $cred -AcceptKey

    Invoke-SSHCommand -SSHSession $ssh -Command $_.Command

    Remove-SSHSession -SSHSession $ssh

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
ganapa2000
Hot Shot
Hot Shot
Jump to solution

Hi LucD,

What is the use of % in the loop { ?

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

The % is an alias for ForEach-Object.
The code block is executed for each row in the CSV


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
ganapa2000
Hot Shot
Hot Shot
Jump to solution

Thanks for the clarification

Reply
0 Kudos