Search code examples
rcommand-linewinscp

Execute wincsp command line arguments from within R


I have some command line batch code which I can run in my windows command prompt just fine. I'm basically pushing a local file text file to a remote server using WinSCP command line arguments - https://winscp.net/eng/docs/commandline. These are the commands I use, in order:

to open up winscp command line:

winscp

then to open connection to my server through ssh:

open sftp://myUserName:[email protected]

upload file to remote server:

put directoryMyLocalFileIsIn\fileToUpload.csv /locationOnRemoteServer/whatToNameFileOnRemoteServer.csv

then close connection:

close

This all works fine. But, I want to run this all from within RStudio.. My issue - after I run:

shell.exec("winscp")

I can see the winscp shell is opened up. But when I try and run my next commands like these:

shell.exec("open sftp://myUserName:[email protected]")

It just doesnt run in that winscp shell that opened up.. I've also used all sorts of combinations of R commands like shell, system2 and shell.

Again, I can open up the winscp shell successfully from within R. But I cant figure out how to then run commands in that shell. Anyone know how to do this?

Thank you.


Solution

  • You need to call WinSCP and specify all commands using a single call from R. The best way to do this is to save your WinSCP commands in a single text file, e.g. myscript.txt:

    open sftp://myUserName:[email protected]
    put directoryMyLocalFileIsIn\fileToUpload.csv /locationOnRemoteServer/whatToNameFileOnRemoteServer
    exit
    

    Then, from the command line, you can call WinSCP as follows (see the WinSCP documentation):

    winscp.com /script=myscript.txt
    

    (you might need to specify the exact path for WinSCP and myscript.txt)

    Finally, to accomplish this from R, use the system2 command as follows:

    system2(
      "winscp.com",
      args = c("/script=myscript.txt"))
    

    Again, you might need to specify the paths to winscp.com and myscript.txt.