Use WinSCP to transfer log files remotely using Javascript

By: Eskalin  

Normally winscp program is used to connect to a remote machine and transfer files. Recently I wanted to connect to my linux machine from a windows machine to download a file automatically everyday. The linux machine was generating daily log files and the name of the log file keeps changing as the current date. So i wrote this script to connect to that machine remotely and download the file every day by running the script in a scheduler.

Save the below as test.js

Change the path to the file based on where you installed your winscp program,

Then run the file as

cscript /nologo test.js


//Scripts starts from here.

// Local path to download to (keep trailing slash)
var LOCALPATH = "d:\\NASShare\\C5\\billlog\\";
// Remote path to download from (keep trailing slash)
var REMOTEPATH = "/var/log/sipproxyd/billing/";
// Session to connect to
var SESSION = "root:[email protected]";
// Path to
var WINSCP = "c:\\program files\\winscp\\";
// helper function to pad zeroes to the left of number
function pad(n, len)
    var s = n.toString();
    while (s.length < len)
        s = '0' + s;
    return s;
var date = new Date();
// format timestamp
var stamp =
    pad(date.getFullYear(), 4) + '-' +
    pad(date.getMonth(), 2) +  '-' +
    pad(date.getDate(), 2);
// File to download
var FILE = "billing.log." + stamp;
var shell = WScript.CreateObject("WScript.Shell");
run winscp to download the file into timestamped-filename
exec = shell.Exec("\"" + WINSCP + "\"");
    "option batch abort\n" +
    "open \"" + SESSION + "\"\n" +
    "get \"" + REMOTEPATH + FILE + "\" \"" + LOCALPATH + "\"\n" +
// wait until the script finishes
while (exec.Status == 0)

Archived Comments

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)

Comment on this tutorial