扫描指定文件目录下文件,经过scp上传到指定服务器目录下python
由于是经过scp自动上传,无需人工干预,因此须要配置两台服务的ssh免密登陆;shell
假如本次服务器分别为A和B,A上传文件到B,按照以下步骤配置ssh免密登陆环境:服务器
[root@A ~]# ssh-keygen -t rsa -P ''app
#coding=utf-8 """ 做用说明: 经过scp上传文件,须要两台无服务预先配置好ssh无密登陆,至于如何配置 能够网上查看教程。 线程一:扫描指定文件目录下的文件,并添加到全局列表中 线程二:扫描全局列表,把文件上传到指定的服务器中, 上传成功则删除该文件,并从全局列表中移除 """ from threading import Thread, Lock import signal import time import datetime import os import sys ftp_list = [] # 全局列表 flag_time = 5 # 时间阈值,表示当前时间戳与文件最后修改时间大于该值时才操做 ftp_path="/tmp/data" # 示例:要扫描的文件目录 server=" root@192.168.101.22:/data/" # 示例:上传到服务器的文件目录 """ path:要扫描的文件目录 file_list: 将扫描到文件加入该列表中 key: 扫描文件时,有的文件不须要,以key关键词 判断该文件是否为须要的文件 """ def get_file_list(path, file_list, key): files=os.listdir(path) for f in files: if key not in f: continue file_with_path = path+"/"+f if file_with_path in file_list: continue if not os.path.isdir(file_with_path): try: time_str = os.path.getmtime(file_with_path) file_time = int(time_str) now_time = int(time.time()) #print("time :", now_time-file_time) except OSError as err: continue if((now_time-file_time) > flag_time): lock.acquire() file_list.append(file_with_path) lock.release() #print("[## add ##]add file %s to global list"% file_with_path) """ file_list: 扫描文件列表,并把文件上传到服务器, 上传成功后,删除文件,并从全局列表中移除 """ def send_file(file_list): year = datetime.datetime.now().year month = datetime.datetime.now().month day = datetime.datetime.now().day for f in file_list: if f.strip(): #上传到服务指定目录下子目录以 年月日 分类 shell_cmd="scp "+f+server+"/"+str(year)+"/"+str(month)+"/"+str(day) ret_shell=os.system(shell_cmd) #print("shellcmd:",shell_cmd) lock.acquire() file_list.remove(f) lock.release() os.remove(f) #print("[-- remove --]remove file %s "% f) def quit(signum, frame): print("You choose to stop me") sys.exit() """ 线程一:扫描文件目录,将符合要求文件名添加到全局列表中 """ def traverse_dir(): global ftp_list while True: get_file_list(ftp_path, ftp_list, ".bin") time.sleep(2) #print("======================== start to traverse ==========================="); #print("[traverse]:%s"% ftp_list) """ 线程二:扫描全局列表,将文件上传到指定服务器, 上传成功,删除文件,并从全局列表中移除 """ def consume_file(): global ftp_list while True: send_file(ftp_list) time.sleep(2) #print("consume:%s"%ftp_list) if __name__=='__main__': try: signal.signal(signal.SIGINT, quit) signal.signal(signal.SIGTERM, quit) lock = Lock() #建立线程锁 thread_product = Thread(target=traverse_dir) thread_consume = Thread(target=consume_file) thread_product.setDaemon(True) thread_product.start() thread_consume.setDaemon(True) thread_consume.start() while True: pass except Exception, exc: print exc