Search code examples
windowsbatch-filecmdftp

Loop through a list using a batch file


I am attempting to write a batch file to automate the process of rebooting some IP cameras i have on a server.

I have successfully got a batch file to reboot one camera, via ftp, but I'm having trouble understanding how to do it for every ip in the range.

I currently have:

open IP
user
pass
quote site reboot
quote site reboot
quit
echo

saved in a .txt file (ftp.txt) and I call this using a .bat file:

@echo off
set user = Username
set pass = Password
ftp -s:ftp.txt

I want to have a list of the ip addresses used, then have the bat script perform the reboot one by one, and wait for 2 minutes before moving to the next one.

I think i'll need to place the list in the .txt file the use a for loop in the bat.

something like

set ip = iplist(??)  <-- Part causing confusion
for each ip in ftp.txt
  open ip
  user
  pass
  quote site reboot
  quote site reboot
  pause 2 min
quit

Any help would be greatly appreciated!


Solution

  • Here's how I'd do it.
    Modify your script (script00.bat):

    @echo off
    
    for /F %%f in (cameras.txt) do (
        ftp -s:ftp.txt %%f
    )
    

    Notes:

    1. I removed the 2 env vars (user / pass) setting since they were not used anyway

    2. [SS64]: FOR /F is used to iterate through each line of the cameras.txt file

    3. Note the extra argument for FTP (it's the IP)

    4. Store all the camera IPs in a file called cameras.txt (one IP per line)

    5. Because of the 3rd note, the IP is passed as an argument to FTP, so it's no longer required in the ftp.txt file, therefore you should delete the 1st line (open IP)

    Posting the other files content.

    cameras.txt:

    mirrors.kernel.org
    ftp.kr.freebsd.org
    

    ftp.txt:

    anonymous
    pass
    quote site reboot
    quote site reboot
    quit
    echo
    

    Output:

    [cfati@cfati-5510-0:e:\Work\Dev\StackOverflow\q045327836]> script00.bat
    Connected to mirrors.pdx.kernel.org.
    220 Welcome to mirrors.kernel.org.
    200 Always in UTF8 mode.
    User (mirrors.pdx.kernel.org:(none)):
    331 Please specify the password.
    
    230 Login successful.
    ftp> quote site reboot
    550 Permission denied.
    ftp> quote site reboot
    550 Permission denied.
    ftp> quit
    221 Goodbye.
    Connected to daemon.kr.freebsd.org.
    220 daemon.kr.freebsd.org FTP server (Version 6.00LS) ready.
    500 OPTS UTF8 ON: command not understood.
    User (daemon.kr.freebsd.org:(none)):
    331 Guest login ok, send your email address as password.
    
    230 Guest login ok, access restrictions apply.
    ftp> quote site reboot
    500 SITE REBOOT: command not understood.
    ftp> quote site reboot
    500 SITE REBOOT: command not understood.
    ftp> quit
    221 Goodbye.
    

    which I think it's what you're after.

    For more details on FTP command, check: [MS.Learn]: ftp