How to ftp with a batch file?

WindowsBatch FileFtp

Windows Problem Overview


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?

Windows Solutions


Solution 1 - Windows

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 :)

Solution 2 - Windows

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.

Solution 3 - Windows

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

Solution 4 - Windows

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.

Solution 5 - Windows

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

Solution 6 - Windows

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.

Solution 7 - Windows

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"
}

Solution 8 - Windows

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

Solution 9 - Windows

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

Solution 10 - Windows

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 user@somedomain.com
	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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1935683View Question on Stackoverflow
Solution 1 - WindowsOutlierView Answer on Stackoverflow
Solution 2 - Windows0x90hView Answer on Stackoverflow
Solution 3 - WindowsMark SchultheissView Answer on Stackoverflow
Solution 4 - WindowsLasseView Answer on Stackoverflow
Solution 5 - WindowsNotMeView Answer on Stackoverflow
Solution 6 - WindowsOswaldView Answer on Stackoverflow
Solution 7 - WindowskevView Answer on Stackoverflow
Solution 8 - WindowsJustin GoldbergView Answer on Stackoverflow
Solution 9 - WindowsGhayelView Answer on Stackoverflow
Solution 10 - WindowsdroohView Answer on Stackoverflow