开发手册 欢迎您!
软件开发者资料库

Python 多台服务器实现文件及文件夹同步的方法

多台Linux服务器之间传输同步文件,如果手动工作量还是很大,还是应该考虑通过编程来实现。本文主要介绍Python中,通过paramiko或paramiko实现文件及文件夹同步的方法,以及相关的示例代码。

1、使用pexpect实现文件及文件夹同步

使用pexpect可以实现通过编程方式使用帐户和密码登陆,之后通过拷贝scp命令来进行文件和目录的复制同步。代码如下

import pexpectdef doScp(username='root',     aim_ip='192.168.31.11',     password='Aa123456',    source_file_path='/home/root/wonhero',    aim_file_path='/home/',    port=22):    password_key = '.*assword.*'    mkdir = f'ssh {username}@{aim_ip} "if [ ! -d aim_file_path ];then mkdir -p {aim_file_path}; fi"'    command = f'if [ ! -d aim_file_path ];then mkdir -p {aim_file_path}; fi"&&scp {source_file_path}  {username}@{aim_ip}:{aim_file_path}'    print("执行指令: ", command)    try:        execute = pexpect.spawn(mkdir)        execute.expect(password_key)        execute.sendline(password)        execute.expect(pexpect.EOF)        execute = pexpect.spawn(command)        execute.expect(password_key)        execute.sendline(password)        execute.expect(pexpect.EOF)        print("拷贝成功")    except:        print("拷贝失败")def executeRemoteCommand(host_list,source_file_path, aim_file_path):    import threading    thread_list = []    for ip, username, password in host_list:        thread = threading.Thread(target = doScp, args = (username,ip,password,source_file_path,aim_file_path))        thread_list.append(thread)#将生成的线程添加到列表里    for t in thread_list:        t.start() #开始执行线程    for t in thread_list:        t.join() #挂起线程,到所有线程结束if __name__ == '__main__':    executeRemoteCommand([('192.168.31.21','root','Aa123456')],'/home/wonhero','/home/')

2、使用paramiko实现文件及文件夹同步

参考文档:https://github.com/mike-zhang/autoSync

1)default.xml配置文件说明

配置

说明

host 

服务器地址

sshPort 

服务器ssh端口

user 

用户名

password 

密码

localDir 

需要同步的文件夹

remoteDir 

同步到服务器的文件夹

fileExcept 

不同步的文件

2)安装paramiko和watchdog

pip install paramiko
pip install watchdog

3)使用方法

python autoSync.py default.xml

注意:如果有多台服务器,可以新建多个xml配置文件,然后分别执行python autoSync.py config.xml来执行同步。