Skip to content
WindowsTip
2015.11.12 02:53

DOS Batch - FTP Scripts 배치파일

조회 수 5702 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄


DOS Batch - FTP Scripts


File Transfer with FTP, One-File Solutions.



TOP
2008-01-01

Classic FTP - Executing a FTP script

Description:

The FTP command support the "-s:ftpscript.txt" option. The FTP commands listed in ftpscript.txt will automatically run after FTP starts. The FTP command can be started from a batch file.

Example:
  • FTP -v -i -s:ftpscript.txt
See also command line help: "C:>ftp -?"
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
open example.com
username
password
!:--- FTP commands below here ---
lcd c:\MyLocalDirectory
cd  public_html/MyRemoteDirectory
binary
mput "*.*"
disconnect
bye
Script Output:
 DOS Script Output
ftp> open example.com
User (Username:(none)):

ftp> !:--- FTP commands below here ---
ftp> lcd c:\MyLocalDirectory
Local directory now c:\MyLocalDirectory.
ftp> cd  public_html/MyRemoteDirectory
ftp> binary
ftp> !: mput "*.*"
ftp> disconnect
ftp> bye

TOP
2008-01-01

FTP - Simple Single Batch - FTP script and batch in a single file

Description:

Embed FTP script into a batch script. Add this line at the beginning of the FTP script:

@ftp -i -s:"%~f0"&GOTO:EOF

The "FTP -s:ftpscript.txt" option executes a FTP script wheres "%~f0" resolved to the name of the running batch file. "GOTO:EOF" ends the batch script and makes sure the FTP script doesn`t run as part of the batch. 
Good: You end up with only one file that contains the batch script and the FTP script combined. 
Minor flaw: The batch command in the first line causes an "Invalid command." error when executed in FTP context, however the FTP execution will continue.

Features:
  • Single file to distribute combining batch and FTP script
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
@ftp -i -s:"%~f0"&GOTO:EOF
open example.com
username
password
!:--- FTP commands below here ---
lcd c:\MyLocalDirectory
cd  public_html/MyRemoteDirectory
binary
mput "*.*"
disconnect
bye
Script Output:
 DOS Script Output
ftp> @ftp -i -s:"%~f0"&GOTO:EOF
Invalid command.
ftp> open example.com
User (Username:(none)):

ftp> !:--- FTP commands below here ---
ftp> lcd c:\MyLocalDirectory
Local directory now c:\MyLocalDirectory.
ftp> cd  public_html/MyRemoteDirectory
ftp> binary
ftp> !: mput "*.*"
ftp> disconnect
ftp> bye

TOP
2009-12-06

FTP - Automatic Login - Automatically login to your FTP session with a single click

Description:

If you frequently find yourself calling FTP from the command line, each time having to login and change directory and change FTP modes, until you finally get where you want be in order to do some real work then you may wish to get there with a singe click.

This little batch can connect to your FTP server and logs you in before it gives you the prompt. You can easily add more FTP commands to it, like changing directories or switching to binary mode or whatever you like to be done before taking over control on the FTP prompt.

The FTP connection information is embedded within the batch itself. The batch connects to an FTP server by executing itself in FTP context using the FTP -s option. Once executing in FTP context it executes all FTP commands listed in the file. By omitting the final FTP "bye" command it will stop at the FTP prompt and wait for user input.

Optionally a FTP script can be provided as input stream, that way multiple FTP scripts can share the same login information. Example:

FtpLogin.bat <script1.ftp

Script:Download: FtpLogin.bat  
1.
2.
3.
4.
5.
@ftp -i -s:"%~f0"&GOTO:EOF
open example.com
username
password
pwd
Script Output:
 DOS Script Output
ftp> @ftp -i -s:"%~f0"&GOTO:EOF
Invalid command.
ftp> open example.com
Connected to example.com.
220-
220 FTP Server ready
User (example.com:(none)):
331 Password required

230 User logged in
ftp> pwd
257 "/" is the current directory
ftp>

TOP
2009-12-06

FTP Scripts Sharing Login Info - Manage the FTP login separately from your FTP scripts

Description:

If you have multiple FTP scripts that all use the same login information to your FTP site then you may wish to manage the login information separately from your FTP scripts in a single place. That way if the username, password or hostname for the FTP connection changes you only need to edit a single place instead of having to edit all FTP scripts one by one.

This automatic login script (also described in detail earlier) can be used to execute different FTP scripts that share the same login information stored within the batch file.

Example: FtpLogin.bat script1.ftp

Note: The FTP scripts passed into the batch must have the login sequence removed.

Note: The FTP script executes even if the connection sequence fails potentially causing `Not connected` and other errors. This is no different from regularly executing FTP with -s option.

Script:Download: FtpLoginSharing.bat  
1.
2.
3.
4.
@type %1|ftp -i -s:"%~f0"&GOTO:EOF
open example.com
username
password

TOP
2008-10-17

FTP - Resolving Environment Variables - Creating FTP script on the fly at runtime and using variables within the FTP script

Description:

This batch executed the FTP script embedded within the batch. All variables in the FTP script will be resolved.

The FOR loop extracts the FTP script into a temporary file. It the ECHO command is being CALLed for each line in order to resolve the variables.

Variables can be used within the FTP script the same way as in a batch script, including any string manipulation and command line arguments like %1 %2 %~n0 %* and so on.

All batch lines start with semicolon so that they will be ignored by the FOR loop. Semicolon is the default end-of-line (EOL) character used by the FOR command.

Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
;@echo off
;(for /f "usebackq delims=" %%A in ("%~f0") do call echo.%%A)>"%temp%\%~n0.ftp"
;ftp -i -s:"%temp%\%~n0.ftp"
;GOTO:EOF

open example.com
username
password
!:--- FTP commands below here ---
cd public_html/%COMPUTERNAME%
binary
hash on
%*
disconnect
bye

TOP
2010-02-05

FTP - Download Only New Files - Ftp script to download only files that don`t exist in local folder, i.e. to avoid overwrite

Description:This batch connects twice to the FTP server. First time it retrieves a list of files on the FTP server. This list is being trimmed to contain only files that don`t already exist locally. The files in the trimmed list are then downloaded during a second connection.

Note: Since all files are passed into the FTP`s MGET command there might be a limit to the number of files that can be processed at once.

Script:Download: BatchFtpDownloadOnlyNewFiles.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
@Echo Off

REM -- Define File Filter, i.e. files with extension .txt
Set FindStrArgs=/E /C:".txt"

REM -- Extract Ftp Script to create List of Files
Set "FtpCommand=ls"
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
Rem Notepad "%temp%\%~n0.ftp"

REM -- Execute Ftp Script, collect File Names
Set "FileList="
For /F "Delims=" %%A In ('"Ftp -v -i -s:"%temp%\%~n0.ftp"|Findstr %FindStrArgs%"') Do (
    Call Set "FileList=%%FileList%% "%%A""
)

REM -- Extract Ftp Script to download files that don't exist in local folder
Set "FtpCommand=mget"
For %%A In (%FileList%) Do If Not Exist "%%~A" Call Set "FtpCommand=%%FtpCommand%% "%%~A""
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
Rem Notepad "%temp%\%~n0.ftp"

For %%A In (%FtpCommand%) Do Echo.%%A

REM -- Execute Ftp Script, download files
ftp -i -s:"%temp%\%~n0.ftp"
Del "%temp%\%~n0.ftp"
GOTO:EOF


:extractFileSection StartMark EndMark FileName -- extract a section of file that is defined by a start and end mark
::                  -- [IN]     StartMark - start mark, use '...:S' mark to allow variable substitution
::                  -- [IN,OPT] EndMark   - optional end mark, default is first empty line
::                  -- [IN,OPT] FileName  - optional source file, default is THIS file
:$created 20080219 :$changed 20100205 :$categories ReadFile
:$source http://www.dostips.com
SETLOCAL Disabledelayedexpansion
set "bmk=%~1"
set "emk=%~2"
set "src=%~3"
set "bExtr="
set "bSubs="
if "%src%"=="" set src=%~f0&        rem if no source file then assume THIS file
for /f "tokens=1,* delims=]" %%A in ('find /n /v "" "%src%"') do (
    if /i "%%B"=="%emk%" set "bExtr="&set "bSubs="
    if defined bExtr if defined bSubs (call echo.%%B) ELSE (echo.%%B)
    if /i "%%B"=="%bmk%"   set "bExtr=Y"
    if /i "%%B"=="%bmk%:S" set "bExtr=Y"&set "bSubs=Y"
)
EXIT /b


[Ftp Script 1]:S
!Title Connecting...
open example.com
username
password

!Title Preparing...
cd public_html/MyRemoteDirectory
lcd c:\MyLocalDirectory
binary
hash

!Title Processing... %FtpCommand%
%FtpCommand%

!Title Disconnecting...
disconnect
bye

TOP
2010-02-05

FTP - Upload Only New Files - Ftp script to upload only files that don`t exist in remote folder, i.e. incremental upload

Description:This batch connects twice to the FTP server. First time it retrieves a list of files on the FTP server. Local files that are are not in this list will then be uploaded during a second connection.

Note: Since all files are passed into the FTP`s MPUT command there might be a limit to the number of files that can be processed at once.

Script:Download: BatchFtpUploadOnlyNewFiles.bat  
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
@Echo Off
Setlocal Enabledelayedexpansion

REM -- Define File Filter, i.e. files with extension .txt
Set FindStrArgs=/E /C:".txt"

REM -- Extract Ftp Script to create List of Files
Set "FtpCommand=ls"
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
Rem Notepad "%temp%\%~n0.ftp"

REM -- Execute Ftp Script, collect File Names
Set "FileList="
For /F "Delims=" %%A In ('"Ftp -v -i -s:"%temp%\%~n0.ftp"|Findstr %FindStrArgs%"') Do (
    Call Set "FileList=%%FileList%% "%%A""
)

REM -- Extract Ftp Script to upload files that don't exist in remote folder
Set "FtpCommand=mput"
For %%A In (%FileList%) Do set "Exist["%%~A"]=Y"
For /F "Delims=" %%A In ('"dir /b "%localdir%"|Findstr %FindStrArgs%"') Do (
    If Not defined Exist["%%~A"] Call Set "FtpCommand=%%FtpCommand%% "%%~A""
)
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
rem  Notepad "%temp%\%~n0.ftp"

For %%A In (%FtpCommand%) Do Echo.%%A

REM -- Execute Ftp Script, download files
ftp -i -s:"%temp%\%~n0.ftp"
Del "%temp%\%~n0.ftp"
GOTO:EOF


:extractFileSection StartMark EndMark FileName -- extract a section of file that is defined by a start and end mark
::                  -- [IN]     StartMark - start mark, use '...:S' mark to allow variable substitution
::                  -- [IN,OPT] EndMark   - optional end mark, default is first empty line
::                  -- [IN,OPT] FileName  - optional source file, default is THIS file
:$created 20080219 :$changed 20100205 :$categories ReadFile
:$source http://www.dostips.com
SETLOCAL Disabledelayedexpansion
set "bmk=%~1"
set "emk=%~2"
set "src=%~3"
set "bExtr="
set "bSubs="
if "%src%"=="" set src=%~f0&        rem if no source file then assume THIS file
for /f "tokens=1,* delims=]" %%A in ('find /n /v "" "%src%"') do (
    if /i "%%B"=="%emk%" set "bExtr="&set "bSubs="
    if defined bExtr if defined bSubs (call echo.%%B) ELSE (echo.%%B)
    if /i "%%B"=="%bmk%"   set "bExtr=Y"
    if /i "%%B"=="%bmk%:S" set "bExtr=Y"&set "bSubs=Y"
)
EXIT /b


[Ftp Script 1]:S
!Title Connecting...
open example.com
username
password

!Title Preparing...
cd public_html/MyRemoteDirectory
lcd c:\MyLocalDirectory
binary
hash

!Title Processing... %FtpCommand%
%FtpCommand%

!Title Disconnecting...
disconnect
bye






[CentOS] ftp로 백업서버로 백업하기 쉘스크립트


현재 서버는 백업서버로의 접근이 ftp만 가능하다.
telnet이 된다면 백업서버에서 쉘을 작성하면 더 용이할 듯하네 ~
사정이 이러하니 실서버에서 백업서버로 ftp로 백업 파일을 전송한다.

파일, 디비 백업은 다음 포스트에 남기도록 하겠다. (검색하면 정말 많이 나온다)
아래와 같이 백업쉘스크립트를 작성한다. 해당 서버에 맞게 작성하면 될듯하다.

#!/bin/bash

# FTP 현 서버에서 데이터 FTP 전송

TODAY=`date +%Y%m%d` # 오늘날짜 저장
DELETE_DATE=`date -d "-5 days" +%Y%m%d` # 오늘날짜에서 -n일 저장
DELETE_DATE_SQL=`date -d "-5 days" +%Y%m%d` # 오늘날짜에서 -n일 저장
DELETE_DATE_LOG=`date -d "-5 days" +%Y%m%d` # 오늘날짜에서 -n일 저장
YOIL=`date +%a` # 요일을 저장


#ftp set
USERNAME=***
PASSWORD=***
HOST=****
B_DIR=/home/_dev/backup

TGZ_FILE="db.tgz"
TGZ_DIR=${B_DIR}/$(date +%Y%m%d)_*.sql


# 매일백업하는 파일중 오래된 파일 삭제처리
rm -f ${B_DIR}/${DELETE_DATE}_${TGZ_FILE}

# sql 삭제도 여기서 
rm -f ${B_DIR}/${DELETE_DATE_SQL}_*.sql

# 로그파일 삭제
rm -rf /home/_dev/log/${DELETE_DATE_LOG}_ftp_bak_log

# 압축 
tar cfz ${B_DIR}/${TODAY}_${TGZ_FILE} ${TGZ_DIR}

#chmod 777 ${B_DIR}/${TODAY}_${TGZ_FILE}

# 파일 
echo ${B_DIR}/${TODAY}_${TGZ_FILE}

{  
echo user $USERNAME $PASSWORD
echo cd /dbbackup
echo bin # as, bi 전송모드 
#echo hash 
echo prompt
echo lcd ${B_DIR} 
#echo put ${TODAY}_${TGZ_FILE} #하나씩
echo mput ${TODAY}_${TGZ_FILE} #다건
echo bye

} | ftp -n -v $HOST > /home/_dev/log/${TODAY}_ftp_bak_log

요런식으로 작성해서 파일이름은 ftp_backup.sh 하면 되겠다.
요넘을 매일 매일 돌려야 백업이 정상적으로 되겠지요.

cron에 등록한다.

# crontab -e 
# mysql backup ftp send
40 01 * * * /home/_dev/cron/ftp_backup.sh >/dev/null 2>&1

매일 새벽 01:40분에 압축하여 백업서버로 전송하면 끝 ~


로그인 후 댓글쓰기가 가능합니다.

?

List of Articles
번호 분류 제목 날짜 조회 수
817 컴퓨터잡담 파이썬 find, select 사용법 2021.07.30 1441
816 컴퓨터잡담 윈도우 10 절전모드(슬립모드) 예약해제 방법 secret 2021.07.28 499
815 컴퓨터잡담 파이썬 변수값에서 숫자만 추출하기 2021.07.28 1141
814 컴퓨터잡담 파이썬 최대값 두번째 큰값 세번째 큰값 구하기 2021.07.27 5005
813 HTMLPHPMSQL html testing 2021.07.24 3740
812 컴퓨터잡담 파이썬 Beautifulsoup 웹크롤링 차단시 해결방법 2021.07.23 1470
811 컴퓨터잡담 파이썬 엑셀 다루기 - openpyxl 사용법 2021.07.19 4901
810 컴퓨터잡담 파이썬 에러 해결방법 모음 2021.07.19 1537
809 Excel 엑셀에서 "따옴표" 입력하기 2021.07.09 3211
808 컴퓨터잡담 KM Wakeup 절전모드 예약 및 깨우는 프로그램 file 2021.07.08 1763
807 컴퓨터잡담 2021년 플래시 플레이어 웹사이트 크롬에서 접속하는 방법 2021.07.05 2561
806 컴퓨터잡담 파이썬 gspread 사용법 file 2021.06.25 11446
805 컴퓨터잡담 파이썬 for문으로 자동변수 생성하기 2021.06.24 3788
804 컴퓨터잡담 파이썬 멀티라벨 소스 줄이기 2021.06.23 1616
803 컴퓨터잡담 파이썬 리스트에 데이터 삽입하기 2021.06.22 1707
802 컴퓨터잡담 파이썬 문자열b 안에 변수 a를 대치시키려면 크게 세 가지 방법 2021.06.18 2582
801 컴퓨터잡담 파이썬 아나콘다 설치시 오류발생 대처방법 2021.06.16 11534
800 컴퓨터잡담 Python 파일을 exe파일로 컴파일하기 2021.06.16 1611
799 컴퓨터잡담 파이썬 IF문 2021.06.16 5068
798 컴퓨터잡담 파이썬 파라미터 변수값 전달받기 2021.06.16 2040
Board Pagination Prev 1 ... 4 5 6 7 8 ... 46 Next
/ 46

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소