1. 程式人生 > >python實現遠端scp檔案

python實現遠端scp檔案

import sys
import os,re
import pipes
import subprocess
from subprocess import *
from config import * //引數可配置化
import random
from multiprocessing import Pool
def copy_log(log_path_2,ssh_host,file):  //拷貝檔案函式
    os.environ['ssh_host'] = str(ssh_host)
    os.environ['file'] = str(file)
    os.environ['log_path_2'] = str(log_path_2)
    os.system("scp -l 100000 ${ssh_host}:${file} ${log_path_2}/")
    os.system("chmod 777 ${log_path_2}/${log}")

pool = Pool(2)  //開啟多程序
def scp_log(date,log,hj,Date,App):
    if hj == "bx" :
        log_path =log_path_bx +App + '/' + date + '/' +Date
        #ssh_host = " ".join(random.sample(ssh_host_bx,1))
        print log_path
        #print ssh_host
    if hj == "zj" :
        log_path =log_path_zj + App + '/' + date
        #ssh_host = " ".join(random.sample(ssh_host_zj,1))
        print log_path
        #print ssh_host
    file = log_path + '/' + log
    log_file = log_path_2 + '/' + log
    resp = subprocess.call( ['ssh',ssh_host, 'test -e ' + pipes.quote(file)] )  //檢查遠端伺服器檔案是否存在
    print "subprocess..."
    if ( 0 == resp ):
        if (os.access(log_file,os.F_OK)==True):
            res =  "log is exists "
            #print res
            return res;
        else:
            du = Popen( ['ssh',ssh_host, 'du -hm ' + pipes.quote(file)],stdout=PIPE,stdin=PIPE) //檢視檔案大小
            s = du.stdout.read()
            l = s.split('\t')
            size = int(l[0])
            time =(size/12)/60
            res = "檔案將在"+str(time)+"分鐘後拷貝完成"
            #print res
            pool.apply_async(func=copy_log,args=(log_path_2, ssh_host, file,))
            return res

    else:
        res = ('{} does not exist '.format(log))
        return res
        #print res