掃描指定文件目錄下文件,經過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