프로그래밍 언어/python(파이썬)
python2.6으로 ftp 활용하여 특정 디렉토리에 파일 다운로드
hippo 데브옵스
2022. 6. 28. 01:50
- python2에서 ftplib 라이브러리 사용법 참조 가능
- domain_list.txt 파일은 확인하고 싶은 도메인 리스트
python2.6으로 ftp 활용하여 특정 디렉토리에 파일 다운로드 코드 예제
$ vi /root/ftp_file.py #!/bin/python2.6 from ftplib import FTP import os from datetime import date, timedelta def file_read_line(): read_file = [] f = open(os.path.abspath(os.getcwd()) + '/domain_list.txt', 'r') while True: line = f.readline().strip() if not line: break read_file.append(line) f.close() return read_file def get_list_ftp(ftp, now_pwd, all_list=[]): datas = [] try: dir_exist = ftp.cwd(now_pwd) data_list = ftp.nlst() for index, data_name in enumerate(data_list): if data_name =='.' or data_name == '..': continue datas.append(now_pwd+data_name) return datas, dir_exist.split(' ')[0] except: return datas, '500' def download_path(dir_name): test_dir = '/' + dir_name if os.path.isdir(test_dir) is False: os.makedirs(test_dir) return test_dir def download_files(ftp, down_file, download_path): for file in down_file: file_name = (file.split('/')[-1]) path_name = file.replace(file_name, '') ftp.cwd(path_name) try: ftp.retrbinary("RETR %s" % file_name, open(download_path+'/'+file_name,'wb').write) except Exception: print down_load_path, "/", file_name, "is downloaded failed" if __name__=="__main__": ftp = FTP('FTP 접속 IP') ftp.login('FTP ID','FTP PW') ftp.encoding='cp949' #print ftp.getwelcome() domains = file_read_line() for domain in domains: all_list, down_status = get_list_ftp(ftp,'/'+domain+'/') if down_status != '250': print '/'+domain+'/ director is not exist' continue down_dir = download_path(domain) #file download download_files(ftp, all_list, down_dir) # ftp connect close ftp.quit()
FTP 서버에서 다운받을 디렉토리 리스트
- a와 같이 FTP 서버에 존재하지 않는 디렉토리는 다운로드에 제외
- 도메인을 추가하려면 마지막 줄에 추가하면 됨
$ cat /root/domain_list.txt google.com a # 오류발생함으로 원래는 삭제되지만, 테스트를 위해서 투입 baidu.com
FTP 추출 python2.6 스크립트 실행
$ python2 /root/ftp_file.py