您的位置:首页 > 编程语言 > Python开发

python 多线程复制文件同步

2013-02-04 15:32 375 查看
最近想做一个通过一台机器可以同时管理多台服务器,也就是多线程控制服务器,可以通过ssh管理apache、mysql等等,于是就自己动手做了一个多线程复制文件同步,功能不是很完整,不过基本功能可以实现,其他的管理也是同样的道理,大家有什么好的建议,希望多多指点。

[root@localhost opt]# cat expect.sh
expect -c "
set timeout 1200;
spawn /usr/bin/scp -r $1 $4@$2:$3
expect {
\"*yes/no*\" {send \"yes\r\"; exp_continue}
\"*password*\" {send \"$5\r\";}
}
expect eof;"

以上是shell脚本,可以通过expect实现scp复制密码自动输入功能,格式:./expect.sh [同步文件] [IP] [远程存放的目录][远程主机用户名][密码],下面是python代码

[root@localhost opt]# cat d.py
#-*- encoding=UTF-8 -*-
import time
import os
import sys
import threading as thread
class Thread1(thread.Thread):
def __init__(self):
thread.Thread.__init__(self)
self.lock = thread.RLock()
self.flag = True
self.count = 0
def run(self):
print 'scp复制第一个'
self.lock.acquire()
os.system('sh expect.sh 1.txt 192.168.251.66 /home root redhat')
self.lock.release()
print '第一个线程结束'

class Thread2(thread.Thread):
def __init__(self,event):
thread.Thread.__init__(self)
self.event = event
def run(self):
self.event.wait()
os.system('./expect.sh 1.txt 192.168.251.67 /home root redhat')
self.event.clear()
print '第二个线程结束'

print '开始运行程序'
event = thread.Event()
test1 = Thread1()
test2 = Thread2(event)
test1.start()
test2.start()
test1.join()
event.set()
test2.join()
print '程序运行结束'
[root@localhost opt]# cat d.py
#-*- encoding=UTF-8 -*-
import time
import os
import sys
import threading as thread
class Thread1(thread.Thread):
def __init__(self):
thread.Thread.__init__(self)
self.lock = thread.RLock()
self.flag = True
self.count = 0
def run(self):
print 'scp复制第一个'
self.lock.acquire()
os.system('sh expect.sh 1.txt 192.168.251.66 /home root redhat')
self.lock.release()
print '第一个线程结束'

class Thread2(thread.Thread):
def __init__(self,event):
thread.Thread.__init__(self)
self.event = event
def run(self):
self.event.wait()
os.system('./expect.sh 1.txt 192.168.251.67 /home root redhat')
self.event.clear()
print '第二个线程结束'

print '开始运行程序'
event = thread.Event()
test1 = Thread1()
test2 = Thread2(event)
test1.start()
test2.start()
test1.join()
event.set()
test2.join()
print '程序运行结束'

以下是执行python脚本:

[root@localhost opt]# python d.py
开始运行程序
scp复制第一个
spawn /usr/bin/scp -r 1.txt root@192.168.251.66:/home
root@192.168.251.66's password:
1.txt                                         100%    0     0.0KB/s   00:00
第一个线程结束
spawn /usr/bin/scp -r 1.txt root@192.168.251.67:/home
root@192.168.251.67's password:
1.txt                                         100%    0     0.0KB/s   00:00
第二个线程结束
程序运行结束

以上操作即可完成简单的同步操作,下次给大家写一些监控事件自动同步脚本,谢谢大家支持

本文出自 “游造技术博客” 博客,谢绝转载!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: