SoFunction
Updated on 2024-10-28

python execute scp command to copy files and folders to the remote host directory method

System environment centos7

python2.7

Start by installing inspect on your operating system


[root@V71 python]# vi 

#!/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 = ( SCP_CMD , stdout=, stderr=, shell=True)
  ()

  (SCP_CMD)
  
  
scpFileToRemoteNode("root","192.168.156.72","Password.","/tmp/var/log","/etc/",22)

 

executable script:

[root@V71 python]# python  
execute SCP_CMD:  
      expect -c "
      set timeout 300 ;
      spawn scp -P 22 -r /tmp/var/log [email protected]:/etc/ ;
      expect *assword* { send cryptographic\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     

 

The above this python execute scp command to copy files and folders to the remote host of the directory method is all that I have shared with you, I hope to be able to give you a reference, and I hope you will support me more.