Chinaunix首页 | 论坛 | 博客
  • 博客访问: 511105
  • 博文数量: 78
  • 博客积分: 995
  • 博客等级: 准尉
  • 技术积分: 1462
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-15 20:22
个人简介

技术中沉思的时候最快乐,问题得到完美解决的时候最有成就感!

文章分类

全部博文(78)

文章存档

2013年(39)

2012年(37)

2011年(2)

分类: Python/Ruby

2012-05-16 16:00:15

前面一篇博文说到系统发布,维护的痛,于是尝试学习 fabric:

1,装 python2.7(系统自带的2.4版本太低了)
2,装 pip
3,pip install fabric

非常简单,可以参考网上的教程;

4,阅读docments,使用很简单;一个小时后,我写出了下面的玩意:

点击(此处)折叠或打开

  1. from fabric.api import env, run, cd, hosts
  2. from fabric.colors import *

  3. env.passwords = {"***":'***', \
  4.         "***" : "****"}

  5. env.hosts = ['****', 'xxxx']

  6. @hosts('xxxxxx', 'ooooo', 'xxxooxx')
  7. def host_type():
  8.         run('uname -s')
  9.         with cd('/usr/local/xxx'):
  10.                 ret = run('ls -l')
  11.                 print "====================="
  12.                 print ret.succeeded,ret.return_code
  13.                 print ret
  14.                 print "====================="



  15. def excute_file(shell_file):
  16.         shell = ""
  17.         try:
  18.                 fd = open(shell_file, "r")
  19.                 shell = fd.read()
  20.         except:
  21.                 print "cant open file"
  22.                 exit()

  23.         print(red("\n---------------start shell-------------------------------- |%s|\n"%(env.host)))
  24.         run(shell)
  25.         print(green("---------------end shell---------------------------------- |%s|\n\n"%(env.host)))

注:1)  passwords 直接写到里面去了,这样就不用每次去输入密码了(蛋疼)
      2)  首先参照教程写了个 host_type 的玩意,掌握了基本的用法后,觉得如果真要在实际项目中应用
   貌似也挺不方便的,在python里面写shell脚本:一,太难看;二,不适合比较复杂比较大的脚本;
   所以感觉直接在 python 里面写这类脚本,基本没有实际意义,于是尝试了另外一种方法:

      3)  把这个 python 脚本当作壳子,真正的 shell 放入一个单独的shell脚本中去,这样,就和平时写
   脚本没什么区别了,可以写的很大,写的很复杂了;然后在 python 中加载这个shell,然后调用
   run(load_str);试了下,果然ok;

调用方法:fab excute_file:a.sh -f a.py
a.sh 随便写了几行:

点击(此处)折叠或打开

  1. cd /usr/local/xxx;
  2. ls -lh;
  3. if [ -d rc ];then
  4.         du -lh rc
  5. else
  6.         echo "***** no rc *****"
  7. fi

以后可以用这个去发布系统和管理系统了

good job
阅读(2756) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~