当前位置: 移动技术网 > IT编程>脚本编程>Python > Python实现远程文件自动打包并下载的方法

Python实现远程文件自动打包并下载的方法

2018年01月28日  | 移动技术网IT编程  | 我要评论

莱茵河的萝莱莉,死神来了5快播,北京生二胎新政策2014

Linux系统集群中,通常需要批量远程执行Linux命令,并且双向同步文件的操作,本文通过使用spawn()方法执行ssh、scp命令的思路实现,具体代码如下:

# -*- coding:UTF-8 -*-
'''

@author: liuyazhuang
'''
import pexpect
import sys
from com.lyz.chapter5.sshfile import fout

#定义目标主机
ip = "192.168.209.121"
#定义目标用户
user = "root"
#目标密码
passwd = "sfsdhfsdhd"
#目标主机nginx日志文件
target_file = "/data/logs/nginx_access.log"

#运行ssh命令
child = pexpect.spawn('/usr/bin/ssh', [user+'@'+ip])
#输入、输出日志写入mylog.txt
fout = file('mylog.txt', 'w')
child.logfile = fout

try:
    #匹配password字符串,(?i)表示不区别大小写
    child.expect('(?i)password')
    child.sendline(passwd)
    child.expect('#')
    child.sendline('tar -czf /data/nginx_access.tar.gz' + target_file)
    
    child.expect('#')
    print child.before
    child.sendline('exit')
    fout.close()

#定义EOF异常处理
except EOF:
    print "expect EOF"
    
#定义timrout异常处理
except TIMEOUT:
    print 'except timeout'

#启动scp远程拷贝命令,实现将打包好的nginx日志复制到本地/home目录    
child = pexpect.spawn('/usr/bin/scp', [user + "@" + ip + ':/data/nginx_access.tar.gz','/home'])
fout = file('mylog.txt', 'a')
child.logfile = fout

try:
    child.expect('(?i)password')
    child.sendline(passwd)
    #匹配缓冲区EOF(结尾),保证文件复制正常完成
    child.expect(pexpect.EOF)
#定义EOF异常处理
except EOF:
    print "expect EOF"
    
#定义timrout异常处理
except TIMEOUT:
    print 'except timeout'

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网