How do I upload a file to an FTP server using a batch script?

48,938

You have to put the ftp commands to a separate file. You cannot put lines you otherwise type on terminal to .bat file and expect it to behave identically. The .bat file can include only Windows commands. When you run the ftp command from the batch file, it waits for its commands. It does not know about the .bat file, so it cannot read the commands from there.

So put your commands to a separate text file (e.g. ftp.txt).

open 142.245.30.165 21
TESTA9MS
test11
binary
put E\PGP\test_pg
quit

And run it from the .bat file like:

ftp -s:ftp.txt
pause

If you really need to use a dynamic file name (from an environment variable), you need to create the text file on-the-fly. The ftp does not support variables.


If you use a better FTP client, you might be able to both have the commands in the batch file and use the environment variables.

For example with WinSCP:

set MyPath=E\PGP\test_pg

winscp.com /command ^
    "open ftp://TESTA9MS:[email protected]" ^
    "put ""%MyPath%""" ^
    "exit"

pause

For an introduction to scripting with WinSCP see:
https://winscp.net/eng/docs/guide_automation

There's also a guide to Converting Windows FTP script to WinSCP script.

(I'm the author of WinSCP)

Share:
48,938

Related videos on Youtube

abhayk
Author by

abhayk

Updated on September 18, 2022

Comments

  • abhayk
    abhayk over 1 year

    I have created a batch file called FTP_automation.bat which contains the code below.

    SET MyPath=E\PGP\test_pg
    ftp
    open 142.245.30.165 21
    TESTA9MS
    test11
    binary
    put %MyPath%
    quit
    Pause
    

    When I am running FTP_automation.bat, it's not uploading the file which I am passing the parameter.

    The script stops after ftp which is mentioned in the batch file, and it's not connecting to the IP address and port number which I have passed in the batch file.

    If I manually typed these commands it was working perfectly. What correction am I supposed to do to this code?

    • Dude named Ben
      Dude named Ben almost 9 years
      Assuming the sequence is correct, it's maybe sending the commands too quickly . There are plenty of free tools to do batch ftp correctly. Don't reinvent the wheel...
    • Dude named Ben
      Dude named Ben almost 9 years