Example of Automatic Packaging and Downloading of Remote Files Implemented by Python

  • 2021-07-18 08:16:21
  • OfStack

This paper describes the automatic packaging and downloading function of remote files realized by Python. Share it for your reference, as follows:

1-point eye

In the cluster operation of Linux system, it is often necessary to execute Linux commands in batches and synchronize files in both directions.

This example is implemented by using the spawn () method to execute the ssh, scp commands.

2 code


import pexpect
import sys
ip="192.168.0.104"
user="root"
passwd="123456"
target_file="/data/test.txt"
child = pexpect.spawn('/usr/bin/ssh', [user+'@'+ip])
fout = file('mylog.txt','w')
child.logfile = fout
try:
  child.expect('password: ')
  child.sendline(passwd)
  child.expect('#')
  child.sendline('tar -czf /data/test.tar.gz '+target_file)
  child.expect('#')
  print child.before
  child.sendline('exit')
  fout.close()
except pexpect.EOF:
  print "expect EOF1"
except pexpect.TIMEOUT:
  print "expect TIMEOUT1"
child = pexpect.spawn('/usr/bin/scp', [user+'@'+ip+':/data/test.tar.gz','/home'])
fout = file('mylog.txt','a')
child.logfile = fout
try:
  child.expect('(?i)password')
  child.sendline(passwd)
  child.expect(pexpect.EOF)
except pexpect.EOF:
  print "expect EOF2"
except pexpect.TIMEOUT:
  print "expect TIMEOUT2"

3 Running


[root@localhost pymaintain]# python 5_3_3.py
tar -czf /data/test.tar.gz /data/test.txt
tar: Removing leading `/' from member names

Output of 4-day annals


[root@localhost pymaintain]# cat mylog.txt
Kernel \r on an \m
root@192.168.0.104's password: 123456
Last login: Sun Feb 24 16:20:25 2019 from 192.168.0.120
hello cakin24!
[root@slave2 ~]# tar -czf /data/test.tar.gz /data/test.txt
tar -czf /data/test.tar.gz /data/test.txt
tar: Removing leading `/' from member names
[root@slave2 ~]# exit
Kernel \r on an \m
root@192.168.0.104's password: 123456
test.tar.gz                  100% 115  40.3KB/s  00:00

More readers interested in Python can check the topics of this site: "Summary of Python File and Directory Operation Skills", "Summary of Python Socket Programming Skills", "Python Data Structure and Algorithm Tutorial", "Summary of Python Function Use Skills", "Summary of Python String Operation Skills" and "Introduction and Advanced Classic Tutorial of Python"

I hope this article is helpful to everyone's Python programming.


Related articles: