Python利用pexpect实现SCP批量文件同步脚本

追风的人
追风的人
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍两种基于Python和pexpect库的SCP批量文件同步方案。第一种方案遍历指定源目录列表,将所有文件同步至目标主机的/tmp目录。第二种方案通过字典映射源路径与目标路径,在同步前检测并创建远程目录,同时输出详细的同步日志,适用于更复杂的目录结构同步需求。

该脚本的主要功能是将源主机指定列表路径下的所有文件,批量同步到目标主机的/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利用pexpect实现SCP批量同步文件的实现方法,就是本文分享的全部内容。希望这些示例能为您提供参考,也欢迎大家继续支持本站获取更多技术内容。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表