VBScript to download files via SFTP using WinSCP fails with Unable to use key file (unable to open file)

4.2k views Asked by At

I am trying to download some files from a remote directory via SFTP using WinSCP.

Till now I have this VBScript. Please note, the connection to SFTP server is set up via private key (.ppk file).

The code goes like below:

Function SFTPDownload(byVal sLocalPath, byVal sRemotePath, byVal sRemoteFile)

    Set oFTPScriptFSO = CreateObject("Scripting.FileSystemObject")
    Set oFTPScriptShell = CreateObject("WScript.Shell")

    sRemotePath = Trim(sRemotePath)
    sLocalPath = Trim(sLocalPath)

    sOriginalWorkingDirectory = oFTPScriptShell.CurrentDirectory
    oFTPScriptShell.CurrentDirectory = sLocalPath

    sFTPScript = sFTPScript & "option batch on" & vbCRLF
    sFTPScript = sFTPScript & "option confirm off"& vbCrLf
    sFTPScript = sFTPScript & "option transfer binary" & vbCrLf
    sFTPScript = sFTPScript & "open username:@sftp.server.com:22 -privatekey=mypriviatekey.ppk" & vbCrLf
    sFTPScript = sFTPScript & "cd " & sRemotePath & vbCrLf
    sFTPScript = sFTPScript & "get " & sRemoteFile & vbCRLF
    sFTPScript = sFTPScript & "close" & vbCrLf
    sFTPScript = sFTPScript & "exit" & vbCrLf


    sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%")
    sFTPTempFile = sFTPTemp & "\" & oFTPScriptFSO.GetTempName

    'Write the input file for the sftp command to a temporary file.
    Set oFTPScript = oFTPScriptFSO.CreateTextFile(sFTPTempFile, True)
    oFTPScript.WriteLine(sFTPScript)
    oFTPScript.Close
    Set oFTPScript = Nothing  

    sCmd = """C:\Program Files (x86)\WinSCP\WinSCP.com"" -script=" & sFTPTempFile 
    oFTPScriptShell.run sCmd

    Wscript.Sleep 1000

    ' Get rid of temp file used for input to sftp
    oFTPScriptFSO.DeleteFile(sFTPTempFile)

    Set oFTPScriptFSO = Nothing
    Set oFTPScriptShell = Nothing
    End Function

    Dim myResult
    myResult = SFTPDownload("F:\WLMS_TEAM\TOUHID\TT Files\", "/done", "EE*.csv")

The scripts opens the WinSCP command prompt and gives me this:

Unable to use key file (unable to open file)

Any idea how can I make it work?

1

There are 1 answers

0
Touhid K. On BEST ANSWER

I found the solution. There was nothing wrong with the code.

I just modified the script file to include full path of private key like below:

option batch on
option confirm off
option transfer binary
open btwsale:@sftp.server.com:22 -privatekey="C:\Program Files (x86)\WinSCP\mypriviatekey.ppk"
cd /done
lcd "C:\Program Files (x86)\WinSCP\"
get EE*.csv
exit