|
楼主 |
发表于 2006-3-6 13:06:29
|
显示全部楼层
最终就是要实现能够定时使用 ssh 从远端取得文件,比如日志,每小时或每天。但是需要使用 python。
我现在的实现如下:
- #!/usr/bin/python
- # -*- encoding: UTF-8 -*-
- import os
- import time
- import pexpect
- import tarfile
- class ft_handler:
- def __init__(self, info):
- self.user = info['user']
- self.host = info['host']
- self.passwd = info['passwd']
- self.method = info['method']
- self.regexp = info['regexp']
- self.srcdir = info['srcdir']
- self.dstdir = info['dstdir']
- self.files = info['files']
- def getfile(self, srcdir = '', dstdir = '', files = ''):
- if srcdir: self.srcdir = srcdir
- if dstdir: self.dstdir = dstdir
- if files: self.files = files
- if self.method == 'ssh.pexpect':
- cmd = 'ssh %s@%s "cd %s; find . | grep %s >tmplist; tar -T tmplist -c -z -f tmp.tgz"' \
- % (self.user, self.host, self.srcdir, self.files)
- self.ssh_pexpect(cmd, 300)
- if not os.path.isdir(self.dstdir): os.makedirs(self.dstdir)
- cmd = 'scp %s@%s:%s/tmp.tgz %s/' % (self.user, self.host, self.srcdir, self.dstdir)
- self.ssh_pexpect(cmd, 600)
- cmd = 'ssh %s@%s "cd %s; rm tmplist tmp.tgz"' % (self.user, self.host, self.srcdir)
- self.ssh_pexpect(cmd)
- tar = tarfile.open('%s/tmp.tgz' % self.dstdir, 'r:gz')
- for T in tar: tar.extract(T, self.dstdir)
- os.remove('%s/tmp.tgz' % self.dstdir)
- # elif self.method == 'ssh.paramiko':
- def ssh_pexpect(self, cmd, timeout=30):
- print cmd
- T = time.time()
- ssh = pexpect.spawn(cmd, timeout=timeout)
- ssh.expect(['password: '])
- ssh.sendline(self.passwd)
- ssh.expect(pexpect.EOF)
- # ssh.sendeof()
- ssh.close()
- print '%d seconds' % int(time.time() - T)
复制代码 |
|