Batch file doesn't execute WinSCP script completely

1

1

I am working on a bat file wherein I have to login to a remove server through SFTP with WinSCP and execute a shell script and get a file to system from the remote server.

Below is the code.

cd C:\Program Files\WinSCP
winscp.com sftp://userid:password@hostname
cd /var/tmp
call ./script.sh 
get /var/tmp/log.txt C:\Preeti\log.txt
exit

However, while executing this file, it stops execution after the second line. I am new to this, please let me know where I am going wrong. Thanks in advance for all the help.

Preeti Maurya

Posted 2016-04-28T12:31:41.530

Reputation: 121

You need to put your winscp commands in a script file

– DavidPostill – 2016-04-28T12:41:18.610

Answers

2

Your batch file is interpreted by Windows command interpreter, the cmd.exe, line-by-line.

So once winscp.com line is reached, the interpreter runs winscp.com and waits for it to exit (what it never does on its own). If it had exited, the interpreter would keep executing the other commands failing the most (as they are not valid Windows commands).

The lines that are actually WinSCP commands, not Windows commands, have to be fed to WinSCP, not to the cmd.exe.

See also WinSCP FAQ Why are some WinSCP scripting commands specified in a batch file not executed/failing?


Before continuing, let me fix your wrong WinSCP syntax. For automation, you do not use the session URL on WinSCP command line, you use open command instead. My following examples will use that instead.


There are two ways:

  • Separate the WinSCP commands into a separate WinSCP script file, say script.txt:

    open sftp://userid:password@hostname
    cd /var/tmp
    call ./script.sh 
    get /var/tmp/log.txt C:\Preeti\log.txt
    exit
    

    And run it like:

    cd C:\Program Files\WinSCP
    winscp.com /script=c:\path\to\script.txt
    
  • Using WinSCP /command command-line switch, you can keep everything in a single file (the batch file) with a syntax like:

    cd C:\Program Files\WinSCP
    winscp.com /command ^
        "open sftp://userid:password@hostname" ^
        "cd /var/tmp" ^
        "call ./script.sh" ^
        "get /var/tmp/log.txt C:\Preeti\log.txt" ^
        "exit"
    

You should read WinSCP guide to automating file transfers to SFTP server.

Martin Prikryl

Posted 2016-04-28T12:31:41.530

Reputation: 13 764

Thank you @Martin Prikryl. I really appreciate your help. – Preeti Maurya – 2016-04-29T02:26:10.540