1. 程式人生 > >python執行scp命令拷貝檔案及資料夾到遠端主機的目錄

python執行scp命令拷貝檔案及資料夾到遠端主機的目錄

系統環境centos7

python2.7

先在作業系統安裝expect

[[email protected] 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)

 

執行指令碼:

[[email protected] python]# python 3s.py 
execute SCP_CMD:   
            expect -c "
            set timeout 300 ;
            spawn scp -P 22 -r /tmp/var/log

[email protected]:/etc/ ;
            expect *assword* { send 密碼\r }  ;
            expect *\r ;
            expect \r ;
            expect eof
            "
    
spawn scp -P 22 -r /tmp/var/log
[email protected]
:/etc/
[email protected]'s password: 
messages                                                                                                                             100%  802KB 802.1KB/s   00:00