Pulling ESXi files and directory listings using WinSCP

I found myself, as I sometimes do, needing an automated process to grab semi-random information off of some ESXi hosts.  However, I would not know some of the server information before the script ran.

Which causes some problems for WinSCP, as it really wants some security in place, specifically it wants to know that you are aware of the host key in advance.

Running WinSCP from the command line w/o an embedded host key returns:

If you trust this host, press Yes. To connect without adding host key to the cache, press No.

but WinSCP has no method of accepting from a script.  However, I then noted before it asked, it provided me with the key:

The server's rsa2 key fingerprint is:
ssh-rsa 2048 f8:9b:4d:f0:e8:b8:23:03:ba:34:5f:47:e0:4d:74:e3

Well, then! If it’s going to give me the key the first time, I’ll just run twice and hand the key back the second time.

Backstory in PowerShell

$password = "samecombinationasmyluggage"
$esxi = esxi.sostechblog.local
rm winscp.txt
rm logwinscp.txt

Prepare the WinSCP batch file

Add-Content -Path winscp.txt "option batch abort"
Add-Content -Path winscp.txt "option confirm off"
$string = "open scp://root:" + $password + "@" + $esxi + ' -hostkey="open"'
Add-Content -Path winscp.txt $string
#Add-Content -Path winscp.txt "get /etc/gcminer/somerandomfile"
Add-Content -Path winscp.txt "ls /etc/gcminer/"
Add-Content -Path winscp.txt "exit"

C:\Progra~2\WinSCP\winscp.exe /console /script=winscp.txt.txt /log=logwinscp.txt |out-Null

I don’t need this iteration to do anything other than get me the host key.  Once run, parse the log file for the key (note the log file is deletes each time, so I only need to worry about the first key found).  I use foreach {$_.matches}|select value to load just the found pattern to a variable

$key = select-string -path logwinscp.txt -pattern "ssh-rsa.*" -list |foreach {$_.matches}|select value

Terrific, now I have the key and can provide it like I knew it all along

rm winscp.txt
rm logwinscp.txt
Add-Content -Path winscp.txt "option batch abort"
Add-Content -Path winscp.txt "option confirm off"
$string = "open scp://root:" + $password + "@" + $esxi + ' -hostkey="' + $key.Value + '"'
Add-Content -Path winscp.txt $string
Add-Content -Path winscp.txt "get /etc/gcminer/somerandomfile"
Add-Content -Path winscp.txt "ls /etc/gcminer/" 
Add-Content -Path winscp.txt "exit" 
C:\Progra~2\WinSCP\winscp.exe /console /script=winscp.txt /log=logwinscp.txt |out-Null

 

This entry was posted in PowerShell, Scripting, Security, VMware and tagged , . Bookmark the permalink.

3 Responses to Pulling ESXi files and directory listings using WinSCP

  1. Obviously you lose ANY security by doing this. Also note that the latest version of WinSCP supports -hostkey=* to accept any host key.

Leave a Reply