dagda1
dagda1

Reputation: 28870

Output ssh command to text file in powershell

I am trying to output the following command to a text file in powershell, but I cannot seem to get it working:

ssh -v [email protected]  | Out-File C:\output.txt

Upvotes: 1

Views: 7061

Answers (2)

Chris Towles
Chris Towles

Reputation: 111

Working on the same problem I made a detail post on my blog How to SSH from Powershell Using Putty\Plink but the short version is this bit of code. But sure you try it after installing putty.

   Function Invoke-SSHCommands {

       Param($Hostname,$Username,$Password, $CommandArray, $PlinkAndPath, $ConnectOnceToAcceptHostKey = $true)

       $Target = $Username + '@' + $Hostname
       $plinkoptions = "-ssh $Target -pw $Password"

       #Build ssh Commands
       $remoteCommand = ""
       $CommandArray | % {$remoteCommand += [string]::Format('{0}; ', $_) }

       #plist prompts to accept client host key. This section will login and accept the host key then logout.
       if($ConnectOnceToAcceptHostKey)
       {
            $PlinkCommand  = [string]::Format('echo y | & "{0}" {1} exit', $PlinkAndPath, $plinkoptions ) 
            #Write-Host $PlinkCommand
            $msg = Invoke-Expression $PlinkCommand
       }

       #format plist command
       $PlinkCommand = [string]::Format('& "{0}" {1} "{2}"', $PlinkAndPath, $plinkoptions , $remoteCommand)


       #ready to run the following command
       #Write-Host $PlinkCommand
       $msg = Invoke-Expression $PlinkCommand
       $msg
    }

    $PlinkAndPath = "C:\Program Files (x86)\PuTTY\plink.exe"
    $Username = "remoteshell"
    $Password = "pa$$w0rd"
    $Hostname = "Linuxhost"

    $Commands = @()
    $Commands += "ls"
    $Commands += "whoami"

    Invoke-SSHCommands -User $Username -Hostname $Hostname -Password $Password -PlinkAndPath $PlinkAndPath -CommandArray $Commands

Upvotes: 2

Torbjörn Bergstedt
Torbjörn Bergstedt

Reputation: 3429

As stated in the post below with using native apps, you could try using Start-Process, e.g.

Start-Process ssh "-v [email protected]" -NoNewWindow -RedirectStandardOutput stdOut.log -RedirectStandardError stdErr.log; gc *.log; rm *.log

Upvotes: 3

Related Questions