python执行scp命令拷贝文件及文件夹到远程主机的目录方法

yipeiwu_com5年前Python基础

系统环境centos7

python2.7

先在操作系统安装expect


[root@V71 python]# vi 3s.py

#!/usr/bin/python
#coding:utf-8
import sys,re
import os
import subprocess

#scp file to remote node.
def scpFileToRemoteNode(user,ip,password,localsource,remotedest,port=22):

  SCP_CMD_BASE = r"""
      expect -c "
      set timeout 300 ;
      spawn scp -P {port} -r {localsource} {username}@{host}:{remotedest} ;
      expect *assword* {{{{ send {password}\r }}}} ;
      expect *\r ;
      expect \r ;
      expect eof
      "
  """.format(username=user,password=password,host=ip,localsource=localsource,remotedest=remotedest,port=port)
  SCP_CMD = SCP_CMD_BASE.format(localsource = localsource)
  print "execute SCP_CMD: ",SCP_CMD
  p = subprocess.Popen( SCP_CMD , stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  p.communicate()

  os.system(SCP_CMD)
  
  
scpFileToRemoteNode("root","192.168.156.72","密码","/tmp/var/log","/etc/",22)

 

执行脚本:

[root@V71 python]# python 3s.py 
execute SCP_CMD:  
      expect -c "
      set timeout 300 ;
      spawn scp -P 22 -r /tmp/var/log root@192.168.156.72:/etc/ ;
      expect *assword* { send 密码\r } ;
      expect *\r ;
      expect \r ;
      expect eof
      "
  
spawn scp -P 22 -r /tmp/var/log root@192.168.156.72:/etc/
root@192.168.156.72's password: 
messages                                                               100% 802KB 802.1KB/s  00:00     

 

以上这篇python执行scp命令拷贝文件及文件夹到远程主机的目录方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python facenet进行人脸识别测试过程解析

Python facenet进行人脸识别测试过程解析

1.简介:facenet 是基于 TensorFlow 的人脸识别开源库,有兴趣的同学可以扒扒源代码: https://github.com/davidsandberg/facenet...

解决Python 使用h5py加载文件,看不到keys()的问题

python 3.x 环境下,使用h5py加载HDF5文件,查看keys,如下: >>> import h5py >>> f = h5py.Fil...

Python实现的多项式拟合功能示例【基于matplotlib】

Python实现的多项式拟合功能示例【基于matplotlib】

本文实例讲述了Python实现的多项式拟合功能。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- #! python2 import numpy as...

python创建线程示例

复制代码 代码如下:import threadingfrom time import sleep def test_func(id):    for i i...

windows10系统中安装python3.x+scrapy教程

windows10系统中安装python3.x+scrapy教程

官网下载就好, https://www.python.org/downloads/release/python-352/ 用installer下载比较方便,它直接把环境变量都帮你配了。...