python2.7經過scp上傳文件到指定服務器

1 說明

實現功能:

  掃描指定文件目錄下文件,經過scp上傳到指定服務器目錄下python

程序結構簡單說明:

  • 包含兩個線程,線程一:掃描文件線程;線程二:消費文件線程;
  • 線程一:掃描指定文件目錄下文件,把符合要求的文件名加入到全局列表中;
  • 線程二:遍歷全局列表,取出文件名,並獲取該文件最後修改時間;
  • 判斷文件最後修改時間與當前時間只差是否大於閾值;
  • 若是大於閾值則經過scp上傳文件到指定服務器,上傳成功刪除文件並從全局列表中移除。

 

2 SSH免密登陸環境

  由於是經過scp自動上傳,無需人工干預,因此須要配置兩臺服務的ssh免密登陸;shell

  假如本次服務器分別爲A和B,A上傳文件到B,按照以下步驟配置ssh免密登陸環境:服務器

1)在A機下生成公鑰/私鑰對。

  [root@A ~]# ssh-keygen -t rsa -P ''app

 
  -P表示密碼,-P '' 就表示空密碼,也能夠不用-P參數,這樣就要三車回車,用-P就一次回車。
  該命令將在/root/.ssh目錄下面產生一對密鑰id_rsa和id_rsa.pub。
  通常採用的ssh的rsa密鑰:
  id_rsa     私鑰
  id_rsa.pub 公鑰
 
  下述命令產生不一樣類型的密鑰
  ssh-keygen -t dsa
  ssh-keygen -t rsa
  ssh-keygen -t rsa1
 

2)把A機下的/root/.ssh/id_rsa.pub 複製到B機的 /root/.ssh/authorized_keys文件裏,先要在B機上建立好 /root/.ssh 這個目錄,用scp複製。

  [root@A ~]# scp /root/.ssh/id_rsa.pub root@192.168.1.181:/root/.ssh/authorized_keys
  root@192.168.1.181's password:
  id_rsa.pub                                    100%  223     0.2KB/s   00:00
 
  因爲尚未免密碼登陸的,因此要輸入一次B機的root密碼。
 

3)authorized_keys的權限要是600

  [root@B ~]# chmod 600 /root/.ssh/authorized_keys
 

4)A機登陸B機

  [root@A ~]# ssh -l root 192.168.1.181
  The authenticity of host '192.168.1.181 (192.168.1.181)' can't be established.
  RSA key fingerprint is 00:a6:a8:87:eb:c7:40:10:39:cc:a0:eb:50:d9:6a:5b.
  Are you sure you want to continue connecting (yes/no)? yes
  Warning: Permanently added '192.168.1.181' (RSA) to the list of known hosts.
  Last login: Thu Jul  3 09:53:18 2008 from root
  [root@B ~]#
 
  第一次登陸是時要你輸入yes。
 
  如今A機能夠無密碼登陸B機了。
 
  想讓A,B機無密碼互登陸,那B機以上面一樣的方式配置便可。

 

3 python源碼

#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
相關文章
相關標籤/搜索