温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中使用scp批量同步文件

发布时间:2021-04-20 17:43:52 来源:亿速云 阅读:323 作者:Leah 栏目:开发技术

本篇文章为大家展示了怎么在python中使用scp批量同步文件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

python是什么意思

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批量同步文件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI