python 多线程复制文件同步
最近想做一个通过一台机器可以同时管理多台服务器,也就是多线程控制服务器,可以通过ssh管理apache、mysql等等,于是就自己动手做了一个多线程复制文件同步,功能不是很完整,不过基本功能可以实现,其他的管理也是同样的道理,大家有什么好的建议,希望多多指点。[*]# 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 [同步文件] [远程存放的目录][远程主机用户名][密码],下面是python代码
[*]# 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 '程序运行结束'
[*]# 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脚本:
[*]# 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
[*]第二个线程结束
[*]程序运行结束
以上操作即可完成简单的同步操作,下次给大家写一些监控事件自动同步脚本,谢谢大家支持
页:
[1]