Python Backup Files
近来书写 Python 脚本进行替换以前的 shell 脚本,发现 Python 优于 shell 的最直观的一点Python 结构明了,可读性高(本人认为)在此做一些记录
本次记录利用 Python Script
1,SVN 备份 ,封装 paramiko的 sftp 和 ssh connection 和 ssh_exec_command
2,删除过期文件
1,SVN 备份
准备:Python Paramiko Install
方法1: 直接使用 pip 进行安装
pip install paramiko
方法2:下载源码进行安装
paramiko-1.15.2.tar.gz 主要文件
ecdsa-0.13.tar.gz 依赖文件
pycrypto-2.6.1.tar.gz 依赖文件
.install ecdsa
tar xzf ecdsa-0.13.tar.gz && cd ecdsa-0.13 && python setup.py install
.install pycrypto
tar xzf pycrypto-2.6..tar.gz && cd pycrypto-2.6. && python setup.py install
.install paramiko
tar xzf paramiko-1.15..tar.gz && cd paramiko-1.15. && python setup.py install
Python Script
#!/usr/bin/env python
# _*_coding:utf-8_*_
# author: 'lonny'
# dateTime: '15/11/16'
# motto: 'Good memory as bad written' import datetime
import os
import tarfile
import subprocess # usvn 备份--------------------------------------------------------------
class Usvn_Backend(object):
# ------------------------------------------------------------------
def __init__(self):
self.date_time = datetime.datetime.now().strftime('%Y-%m-%d-%H')
self.Root_Directory = "/software"
self.back_directory = "usvn"
self.Remote_Send_Dir = "/install/backup/usvnback" # 打包文件------------------------------------------------------------
def Package(self):
global tarfile_name
print "\033[32mWaitIng Packaging..........\033[0m"
os.chdir(self.Root_Directory)
tarfile_name = "%s-%s.tar.gz" % (self.back_directory, self.date_time)
tar = tarfile.open(tarfile_name, "w:gz")
tar.add(self.back_directory)
tar.close()
if os.path.exists(tarfile_name):
print "\033[32m..........Packaging Is SuccessFul!!!\033[32m"
else:
print "\033[32m..........Packaging Is Failed!!!\033[0m" # 执行远程命令传送文件---------------------------------------------------------
class SSHConnection(object):
"""""" # ----------------------------------------------------------------------
def __init__(self, host, username, password, port=22):
"""Initialize and setup connection"""
self.sftp = None
self.sftp_open = False # open SSH Transport stream
self.transport = paramiko.Transport((host, port)) self.transport.connect(username=username, password=password) self.session = self.transport.open_channel(kind='session') # ----------------------------------------------------------------------
def _openSFTPConnection(self):
"""
Opens an SFTP connection if not already open
"""
if not self.sftp_open:
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
self.sftp_open = True # ----------------------------------------------------------------------
#下载文件时需要指定两端文件名
def get(self, remote_path, local_path=None):
"""
Copies a file from the remote host to the local host.
"""
self._openSFTPConnection()
self.sftp.get(remote_path, local_path) # ----------------------------------------------------------------------
#传送文件是需要两端都要指定文件名称
def put(self, local_path, remote_path=None):
"""
Copies a file from the local host to the remote host
"""
self._openSFTPConnection()
self.sftp.put(local_path, remote_path) # ----------------------------------------------------------------------
def run(self, command, nbytes=4096):
# Run Command out|err
stdout_data = []
stderr_data = []
self.session.exec_command(command)
while True:
if self.session.recv_ready():
stdout_data.append(self.session.recv(nbytes))
if self.session.recv_stderr_ready():
stderr_data.append(self.session.recv_stderr(nbytes))
if self.session.exit_status_ready():
break
print "\033[31m*********************\033[0m"
print '\033[32mExit status is: \033[0m', self.session.recv_exit_status()
print "\033[31m*********************\033[0m"
print ''.join(stdout_data)
print ''.join(stderr_data) def close(self):
"""
Close SFTP connection and ssh connection
"""
if self.sftp_open:
self.sftp.close()
self.sftp_open = False
self.transport.close()
self.session.close() if __name__ == '__main__':
try:
try:
import paramiko
except ImportError:
print "\033[32mInstalling Paramiko.........\033[0m"
install_paramiko = "pip install paramiko"
subprocess.call(install_paramiko, shell=True)
# Run Usvn Unpack--------------------------------------------------------------
unpack = Usvn_Backend()
unpack.Package()
# Put UsvnBack Files To Remote Server
Send_Files = SSHConnection(ipaddress, user, password)
#Set local_path Names,remote_path Names
local_path_files = "%s/%s" % (unpack.Root_Directory, tarfile_name)
remote_path_files = "%s/%s" % (unpack.Remote_Send_Dir, tarfile_name)
Send_Files.put(local_path_files, remote_path_files)
#remove tarfiles
os.chdir(unpack.Root_Directory)
os.remove(tarfile_name)
#remove end!!!!
Send_Files.close()
except KeyboardInterrupt:
print "Contorl+C+Z"
2,删除过期文件
#!/usr/bin/env python
# _*_coding:utf-8_*_
# author: 'lonny'
# dateTime: '15/12/15'
# motto: 'Good memory as bad written' import os
import sys
import time #删除文件-----------------------------------------------------------------
def remove(path):
"""
Remove the file or directory
"""
if os.path.isdir(path):
try:
os.rmdir(path)
except OSError:
print "Unable to remove folder: %s" % path
else:
try:
if os.path.exists(path):
os.remove(path)
except OSError:
print "Unable to remove file: %s" % path # 遍历输入的文件夹,查询出number_of_days天前的文件,进行删除---------------------
def cleanup(number_of_days, path):
"""
Removes files from the passed in path that are older than or equal
to the number_of_days
"""
time_in_secs = time.time() - (number_of_days * 24 * 60 * 60)
"""
计算出当前时间与number_of_days天前的毫秒差
"""
for root, dirs, files in os.walk(path, topdown=False):
for file_ in files:
full_path = os.path.join(root, file_)
stat = os.stat(full_path) if stat.st_mtime <= time_in_secs:
remove(full_path) if not os.listdir(root):
remove(root) # ----------------------------------------------------------------------
if __name__ == "__main__":
#sys.argv[1]天数 sys.argv[2]要遍历的目录
days, path = int(sys.argv[1]), sys.argv[2]
cleanup(days, path)
Python Backup Files的更多相关文章
- 贪心:SPOJ Backup Files
BACKUP - Backup Files no tags You run an IT company that backs up computer data for large offices. ...
- [PowerShell] Backup Folder and Files Across Network
## This Script is used to backup folder/files and delete the old backup files. ## Author: Stefanie # ...
- vim+python
#!/bin/bash # install fisa vim config echo '===============================' echo 'start to install ...
- zookeeper与Kafka集群搭建及python代码测试
Kafka初识 1.Kafka使用背景 在我们大量使用分布式数据库.分布式计算集群的时候,是否会遇到这样的一些问题: 我们想分析下用户行为(pageviews),以便我们设计出更好的广告位 我想对用户 ...
- python 代码混淆工具汇总
pyminifier Pyminifier is a Python code minifier, obfuscator, and compressor. Note For the latest, co ...
- Python检查 文件备份是否正常 云备份进程是否正常运行
场景:服务器自动备份数据库文件,每两小时生成一个新备份文件,通过云备份客户端自动上传,需要每天检查是否备份成功. 实现:本脚本实现检查文件是否备份成功,进程是否正常运行,并且发送相关邮件提醒. #! ...
- [python] File path and system path
1. get files in the current directory with the assum that the directory is like this: a .py |----dat ...
- TFS Express backup and restore
When we setup source control server, we should always make a backup and restore plan for it. This ar ...
- [转]Installing python 2.7 on centos 6.3. Follow this sequence exactly for centos machine only
Okay for centos 6.4 also On apu.0xdata.loc, after this install was done $ which python /usr/local/bi ...
随机推荐
- 用Qt写软件系列一:QCacheViewer(浏览器缓存查看器)
介绍 Cache技术广泛应用于计算机行业的软硬件领域.该技术既是人们对新技术探讨的结果,也是对当前软硬件计算能力的一种妥协.在浏览器中使用cache技术,可以大幅度提高web页面的响应速度,降低数据传 ...
- 迭代接口的IEnumerator
我们经常在工作中用到对List,Dictionary对象的Foreach遍历,取出每一项. 其实这个接口很简单,只有一个属性2个方法. [ComVisible(true), Guid("49 ...
- 响应式布局(Responsive layout,RL)的简单Demo
★背景: 响应式布局是Ethan Marcotte在2010年5月份提出的一个概念,简而言之,就是一个网站能够兼容多个终端--而不是为每个终端做一个特定的版本.这个概念是为解决 ...
- CSS浏览器兼容性写法小结
* , ie6,ie7可以识别: _和- , ie6可以识别: !important ,表示高优先级,ie7及以上,firefox都支持,ie6认识带!important的样式属性, ...
- 重新想象 Windows 8.1 Store Apps (90) - 通信的新特性: 通过 HttpBaseProtocolFilter 实现 http 请求的缓存控制,以及 cookie 读写; 自定义 HttpFilter; 其他
[源码下载] 重新想象 Windows 8.1 Store Apps (90) - 通信的新特性: 通过 HttpBaseProtocolFilter 实现 http 请求的缓存控制,以及 cooki ...
- MySQL更新优化
通常情况下,当访问某张表的时候,读取者首先必须获取该表的锁,如果有写入操作到达,那么写入者一直等待读取者完成操作(查询开始之后就不能中断,因此允许读取者完成操作).当读取者完成对表的操作的时候,锁就会 ...
- 启动Tomcat出现“Bad version number in .class file (unable to load class XXX)”解决
转载自:http://blog.csdn.net/justdb/article/details/8067887 主要是jdk版本的不搭配 保证tomcat 的jdk版本 项目的jdk版本 还有就是编译 ...
- 数据库设计==>>MySchool
1.数据库设计的步骤 第一步:需求分析(收集信息) 第二步:绘制 E-R 图 (标示实体 ,找到实体的属性 第三步:将 E-R 图转换成数据库模型图 第四步:将数据库模型图转换成数据表 2.如何绘制 ...
- CentOS6.5 FTP配置
一:安装vsftpd 查看是否已经安装vsftpd rpm -qa | grep vsftpd 如果没有,就安装,并设置开机启动 yum -y install vsftpd chkconfig vsf ...
- jquery TypeError: 'undefined' is not a function (evaluating 'elem.nodeName.toLowerCase()') [jquery.js:1904]错误原因
今天,某个环境报了个js错误,TypeError: 'undefined' is not a function (evaluating 'elem.nodeName.toLowerCase()') [ ...