在一年多之前,我写过一个博客介绍Fabric(Fabric 一个与多台服务器远程交互的Python库和工具),前段时间我也在项目中也大量使用了Fabric来管理很多服务器。
我的博客搭建在一个KVM VPS上,今天也写了一个fabfile来dump数据库、打包WordPress目录,并下载到本地。fabfile代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#!/usr/bin/python # use Fabric to manage all the hosts in perf env. # usage: fab -f vps_fabfile.py download_backup # author: Jay <smile665@gmail.com> from fabric.context_managers import cd #from fabric.context_managers import settings from fabric.operations import * from fabric.api import * from datetime import datetime env.hosts = 'smilejay.cn' env.port = 22 env.user = 'root' env.password = '1234' @task def download_backup(): # backup my WP file and database, download them to the local machine dt = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") local_dir = '/home/jay/backup' with cd('/tmp'): nginx = '/usr/share/nginx' wp_root = '/usr/share/nginx/html' exclude = 'html/wp-content/cache' bk_name = 'wp_%s.tar.gz' % dt clean = 'rm -f wp*.tar.gz' mysql = 'mysqldump -uroot -p1234 -A > %s/mysql-dump.sql' % wp_root tar = 'tar -zcf %s -C %s html --exclude=%s' % (bk_name, nginx, exclude) run(clean) run(mysql) run(tar) get(bk_name, '%s/%s' % (local_dir, bk_name)) |
Github地址:https://github.com/smilejay/python/blob/master/py2014/vps_fabfile.py
当然,我一般也会使用BackWPup插件来备份WordPress;刚好发现,前段时间使用Nginx替代Apache后,BackWPup运行时仍然要写“/var/www/html/wp-content/backwpup-logs/”目录,所以有个权限问题,最近两个月都是运行失败了。后来对这个目录开放了写权限就没问题了。