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

时间:2022-01-08 03:50:46

系统环境centos7

python2.7

先在操作系统安装expect

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
[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/00:00    

以上这篇python执行scp命令拷贝文件及文件夹到远程主机的目录方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/lsysafe/article/details/82977634