pscp多線程傳輸文件


前面說過pscp不支持多線程,所以在此特地實現了一個

程序分三個部分:

1、初始化各種參數,涉及getopt函數的使用

2、重新定義scp,實現傳遞IP然后遠程拷貝

3、啟動多線程調用scp,涉及多線程的啟動和等待線程結束

import sys, getopt
import commands
import threading
p = 1
host_file = ""
source_file = ""
destin_file = ""

#init arguments
opts, args = getopt.getopt(sys.argv[1:], "Hp:h:")
def usage():
    print "python mypscp.py [-p threadNum] [-H] -h hostFile localFile1 ... remoteFullPath"
#print opts
#print args
if '-h' not in str(opts) or len(args) < 2:
    usage()
    sys.exit()
for op, value in opts:
    if op == "-p":
        p = int(str.strip(value))
        if(p < 1):
            usage()
                sys.exit()
    elif op == "-H":
        usage()
            sys.exit()
    elif op == "-h":
        host_file = str.strip(value)
        if(host_file == ""):
            usage()
                sys.exit()
source_file = str.strip(args[0])
if(source_file == ""):
    usage()
    sys.exit()
destin_file = str.strip(args[1])
if(destin_file == ""):
    usage()
    sys.exit()

#define scp()
def scp(ip):
    ip = ip.strip()
    mycommand = 'scp ' + source_file + ' ' + ip + ':'+ destin_file
    #print mycommand
    (status, output) = commands.getstatusoutput(mycommand)
    if(str(status) == '0'):
        print ip,'[SUCCESS]'
    else:
        print status, output

#read ip and start multi-thread
ips = []
threads = []
try:
    with open(host_file) as host:
        for ip in host:
            ips.append(str.strip(ip))
except:
    print host_file, ' is not exist'

ipNum = len(ips)
threadNum = p
times = ipNum / p
yushu = ipNum % p
for i in range(times + 1):
    if(times == 0 or i == times):
        threadNum = yushu
    for j in range(threadNum):
        ip = ips[i*p + j]
        #print ip
        th = threading.Thread(target=scp, args=(ip,))
        threads.append(th)
        th.start()
    for t in threads:
        t.join()

測試結果:

 

ps:對於讀取帶選項參數和Python多線程參考了以下兩篇博客

http://www.jb51.net/article/66539.htm

http://www.cnblogs.com/fnng/p/3670789.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM