[windows] How to ftp with a batch file?

I want a batch file to ftp to a server, read out a text file, and disconnect. The server requires a user and password. I tried

@echo off
pause
@ftp example.com
username
password
pause

but it never logged on. How can I get this to work?

This question is related to windows batch-file ftp

The answer is


You need to write the ftp commands in a text file and give it as a parameter for the ftp command like this:

ftp -s:filename

More info here: http://www.nsftools.com/tips/MSFTP.htm

I am not sure though if it would work with username and password prompt.


Here's what I use. In my case, certain ftp servers (pure-ftpd for one) will always prompt for the username even with the -i parameter, and catch the "user username" command as the interactive password. What I do it enter a few NOOP (no operation) commands until the ftp server times out, and then login:

open ftp.example.com 
noop
noop
noop
noop
noop
noop
noop
noop
user username password
...
quit

This is an old post however, one alternative is to use the command options:

ftp -n -s:ftpcmd.txt

the -n will suppress the initial login and then the file contents would be: (replace the 127.0.0.1 with your FTP site url)

open 127.0.0.1
user myFTPuser myftppassword
other commands here...

This avoids the user/password on separate lines


I have written a script as *.sh file

#!/bin/sh
set -x
FTPHOST='host-address'
FTPUSER='ftp-username'
FTPPASSWD='yourPass'

ftp -n -v $FTPHOST << EOT
ascii
user $FTPUSER $FTPPASSWD
prompt
##Your commands
bye
EOT

Works fine for me


The answer by 0x90h helped a lot...

I saved this file as u.ftp:

open 10.155.8.215 
user
password
lcd /D "G:\Subfolder\"
cd  folder/
binary
mget file.csv
disconnect
quit

I then ran this command:

ftp -i -s:u.ftp

And it worked!!!

Thanks a lot man :)


You can use PowerShell as well; this is what I did. As I needed to download a file based on a pattern I dynamically created a command file and then let ftp do the rest.

I used basic PowerShell commands. I did not need to download any additional components. I first checked if the requisite number of files existed. If they I invoked the FTP the second time with an Mget. I run this from a Windows Server 2008 connecting to a Windows XP remote server.

function make_ftp_command_file($p_file_pattern,$mget_flag)
{
    # This function dynamically prepares the FTP file.
    # The file needs to be prepared daily because the
    # pattern changes daily.
    # PowerShell default encoding is Unicode.
    # Unicode command files are not compatible with FTP so
    # we need to make sure we create an ASCII file.

    write-output "USER" | out-file -filepath C:\fc.txt -encoding ASCII
    write-output "ftpusername" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    write-output "password" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    write-output "ASCII" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    If ($mget_flag -eq "Y")
    {
        write-output "prompt" | out-file -filepath C:\fc.txt -encoding ASCII -Append
        write-output "mget $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    }
    else
    {
        write-output "ls $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
    }

    write-output quit | out-file -filepath C:\fc.txt -encoding ASCII -Append
}


###########################  Init Section ###############################
$yesterday = (get-date).AddDays(-1)
$yesterday_fmt = date $yesterday -format "yyyyMMdd"
$file_pattern = "BRAE_GE_*" + $yesterday_fmt + "*.csv"
$file_log = $yesterday_fmt + ".log"

echo  $file_pattern
echo  $file_log


############################## Main Section ############################
# Change location to folder where the files need to be downloaded
cd c:\remotefiles

# Dynamically create the FTP Command to get a list of files from
# the remote servers
echo "Call function that creates a FTP Command "
make_ftp_command_file $file_pattern N


#echo "Connect to remote site via FTP"
# Connect to Remote Server and get file listing
ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log

$matches=select-string -pattern "BRAE_GE_[A-Z][A-Z]*" C:\logs\$file_log

# Check if the required number of Files available for download
if ($matches.count -eq 36)
{
    # Create the FTP command file

    # This time the command file has an mget rather than an ls
    make_ftp_command_file $file_pattern Y

    # Change directory if not done so
    cd c:\remotefiles

    # Invoke ftp with newly created command file
    ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log
}
else
{
    echo "The full set of files is not available"
}

If you need to pass variables to the txt file you can create in on the fly and remove after.

This is example is a batch script running as administrator. It creates a zip file using some date & time variables. Then it creates a ftp text file on the fly with some variables. Then it deletes the zip, folder and ftp text file.

set YYYY=%DATE:~10,4%
set MM=%DATE:~4,2%
set DD=%DATE:~7,2%

set HH=%TIME: =0%
set HH=%HH:~0,2%
set MI=%TIME:~3,2%
set SS=%TIME:~6,2%
set FF=%TIME:~9,2%

set dirName=%YYYY%%MM%%DD%
set fileName=%YYYY%%MM%%DD%_%HH%%MI%%SS%.zip

echo %fileName%

"C:\Program Files\7-Zip\7z.exe" a -tzip C:\%dirName%\%fileName% -r "C:\tozip\*.*" -mx5

(
    echo open 198.123.456.789
    echo [email protected]
    echo yourpassword
    echo lcd "C:/%dirName%"
    echo cd  theremotedir
    echo binary
    echo mput *.zip
    echo disconnect
    echo bye
) > C:\ftp.details.txt


cd C:\
FTP -v -i -s:"ftp.details.txt"

del C:\ftp.details.txt /f

Use

ftp -s:FileName 

as decribed in Windows XP Professional Product Documentation.

The file name that you have to specify in place of FileName must contain FTP commands that you want to send to the server. Among theses commands are

  • open Computer [Port] to connect to an FTP server,
  • user UserName [Password] [Account] to authenticate with the FTP server,
  • get RemoteFile [LocalFile] to retrieve a file,
  • quit to end the FTP session and terminate the ftp program.

More commands can be found under Ftp subcommands.


Each line of a batch file will get executed; but only after the previous line has completed. In your case, as soon as it hits the ftp line the ftp program will start and take over user input. When it is closed then the remaining lines will execute. Meaning the username/password are never sent to the FTP program and instead will be fed to the command prompt itself once the ftp program is closed.

Instead you need to pass everything you need on the ftp command line. Something like:

@echo off
echo user MyUserName> ftpcmd.dat
echo MyPassword>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo put %1>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat SERVERNAME.COM
del ftpcmd.dat

Using the Windows FTP client you would want to use the -s:filename option to specify a script for the FTP client to run. The documentation specifically points out that you should not try to pipe input into the FTP client with a < character.

Execution of the script will start immediately, so it does work for username/password.

However, the security of this setup is questionable since you now have a username and password for the FTP server visible to anyone who decides to look at your batch file.

Either way, you can generate the script file on the fly from the batch file and then pass it to the FTP client like so:

@echo off

REM Generate the script. Will overwrite any existing temp.txt
echo open servername> temp.txt
echo username>> temp.txt
echo password>> temp.txt
echo get %1>> temp.txt
echo quit>> temp.txt

REM Launch FTP and pass it the script
ftp -s:temp.txt

REM Clean up.
del temp.txt

Replace servername, username, and password with your details and the batch file will generate the script as temp.txt launch ftp with the script and then delete the script.

If you are always getting the same file you can replace the %1 with the file name. If not you just launch the batchfile and provide the name of the file to get as an argument.


Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to batch-file

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH CanĀ“t run .bat file under windows 10 Execute a batch file on a remote PC using a batch file on local PC Windows batch - concatenate multiple text files into one How do I create a shortcut via command-line in Windows? Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat Curl not recognized as an internal or external command, operable program or batch file Best way to script remote SSH commands in Batch (Windows)

Examples related to ftp

Uploading into folder in FTP? Wordpress plugin install: Could not create directory How to setup FTP on xampp Google Drive as FTP Server Fatal error: Call to undefined function mysqli_connect() Filezilla FTP Server Fails to Retrieve Directory Listing FTP/SFTP access to an Amazon S3 Bucket 200 PORT command successful. Consider using PASV. 425 Failed to establish connection PowerShell Connect to FTP server and get files How to use passive FTP mode in Windows command prompt?