python scp 批量同步文件的实现方法

yipeiwu_com6年前Python基础

该脚本用于将源主机列表路径下的所有文件同步于目标主机的/tmp下面

#!/usr/bin/python
# -*- coding:utf-8 -*-

import pexpect
import os
import os.path

src_path = ['/tmp/', '/opt/', '/root/']
dest_host = "192.168.143.201"
dest_path = "/tmp"

for path in src_path:
 file_list = os.listdir(path)
 for files in file_list:
  f = path + files
  cmd = 'scp -r %s %s:%s' % (f, dest_host, dest_path)
  scp = pexpect.spawn(cmd)
  scp.read()

下面的脚本基于第一个脚本做了补充,通过字典列出源主机的路径及对应目标主机的路径 key —> value 的映射关系,并且会去远端进行目录是否存在的检测,以及文件同步过程的详细输出。

#!/usr/bin/python
# -*- coding:utf-8 -*-

import pexpect
import os
import os.path

path_dict = {'/tmp/': '/tmp1/', '/opt/': '/opt1/', '/data/': '/data1/'}
dest_host = "192.168.143.201"

def src_to_dest(path_dict, dest_host):
 ''' 该脚本用于将主机 /tmp,/opt,/data 下的所有文件同步至远程主机 /tmp1,/data1,/opt1 '''

 for path in path_dict:
  file_list = os.listdir(path)

  cmd = 'ssh %s "[ -d %s || mkdir -p %s ]"' % (dest_host, path_dict[path], path_dict[path])
  ssh = pexpect.spawn(cmd)
  ssh.read()

  #dest_path = "ssh %s '[ -d %s ] || mkdir -p %s'" % (dest_host, path_dict[path], path_dict[path])
  #os.system(dest_path)
  for files in file_list:
   src_file = path + files
   print src_file + ' ---> ' + dest_host + ':' + path_dict[path] + files
   cmd = 'scp -r %s %s:%s' % (src_file, dest_host, path_dict[path])
   scp = pexpect.spawn(cmd)
   scp.read()

src_to_dest(path_dict, dest_host)

以上这篇python scp 批量同步文件的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中装饰器高级用法详解

在Python中,装饰器一般用来修饰函数,实现公共功能,达到代码复用的目的。在函数定义前加上@xxxx,然后函数就注入了某些行为,很神奇!然而,这只是语法糖而已。 场景 假设,有一些工作...

python跳过第一行快速读取文件内容的实例

Python编程时,经常需要跳过第一行读取文件内容。简单的做法是为每行设置一个line_num,然后判断line_num是否为1,如果不等于1,则进行读取操作。 相应的Python代码如...

Python操作列表之List.insert()方法的使用

 insert()方法插入对象obj到列表的偏移量索引。 语法 以下是insert()方法的语法: list.insert(index, obj) 参数 &nb...

Python模块、包(Package)概念与用法分析

Python模块、包(Package)概念与用法分析

本文实例讲述了Python模块、包(Package)概念与用法。分享给大家供大家参考,具体如下: Python中”模块”的概念 在开发中,我们会有很多函数,我们可以把这些函数都放到一个文...

python使用 __init__初始化操作简单示例

本文实例讲述了python使用 __init__初始化操作。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- # !/usr/bin/python cl...