首页 > linux > 多线程更新线上服务器

多线程更新线上服务器

2012年11月15日 eric 发表评论 阅读评论

好久没有更新过blog了,把自己写的一个多线程更新的脚本共享给大家,如果有什么疑问过着建议欢迎留言,以后我会把写的一个简单的通过页面更新线上服务的程序open 出来。

写这个脚本当然要说一下场景:
1,有一批web服务器,上面跑着相同的应用,目录结构一样。
2,更新时候注定要备份、删除缓存(不备份小心死人,删除缓存必要啊,不然新上的代码会不生效)
3,更新时必然我们要记录日志,是否连接服务器超时、备份时候成功、更新是否成功。

好了,有了结构,有了日志,有了备份,那么就不怕升级失败了。

先说代码为解决的一个问题,因为要开启多线程,所以日志记录的有点混乱,比如 ip 从 192.166.1.2 更新到 192.168.1.254 ,记录的日志可能第一行记录是 1.2 那么第二行可能记录 1.6 ,不过日志肯定每个服务的连接和返回日志都记录了。

脚本代码主要引入了 paramiko 类,有人说你为何不用 fabric,大哥我用了,他非要执行命令,结合 shell 来执行还是不错的,但是哥我测试想用单个脚本文件执行,我也做过测试,设置 env 环境变量后的确可以,但是比较慢,而且相当麻烦。所以哥我选择了 paramiko 用了一段时间,很稳定速度不错。

废话不多说,那么我们来看下代码:

1 #!/usr/bin/python2.6
  2 #-*- coding:utf-8 -*-
  3 import paramiko
  4 import commands
  5 import pexpect
  6 import  MySQLdb
  7 import logging
  8 import threading
  9 import Queue
 10 import csv
 11 import time
 12
 13 logging.basicConfig(level=logging.INFO,
 14                     format='%(asctime)s %(filename)s %(levelname)s %(message)s',
 15                     datefmt='%a,%d %b %Y %H %M:%s',
 16                     filename='paramiko.log',
 17                     filemode='w')
 18
 19 ## 创建 SSH 连接类
 20 class SSHClient(paramiko.SSHClient):
 21         def call(self, command, bufsize=-1):
 22                 chan = self._transport.open_session()
 23                 chan.exec_command(command)
 24                 stdin = chan.makefile('wb', bufsize)
 25                 stdout = chan.makefile('rb', bufsize)
 26                 stderr = chan.makefile_stderr('rb', bufsize)
 27 ## 获取命令放回状态代码
 28                 status = chan.recv_exit_status()
 29                 return stdin, stdout, stderr, status
 30
 31 ## 创建 rsync 连接类
 32 class rsyncThread():
 33    def __init__(self,host,passwd,code):
 34      self.host = host
 35      self.passwd = passwd
 36      self.code = code
 37    def run(self):
 38        ssh = pexpect.spawn("/usr/bin/rsync -a -c -v --delete %s -e '%s' %s:%s" % (self.code,'ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null',self.host,self.code),timeout=600)
 39        log=open('test.log','a')
 40        ssh.logfile=log
 41        i = ssh.expect(['(yes/no)','password:',pexpect.TIMEOUT,pexpect.EOF])
 42        if i == 0:
 43          ssh.sendline('yes')
 44          ssh.expect('password:')
 45          ssh.sendline(self.passwd)
 46        elif i == 1:
 47          ssh.sendline(self.passwd)
 48        elif i == 2:
 49          return False
 50        elif i == 3:
 51          return False
 52        ssh.expect(pexpect.EOF)
 53
 54 class mysqlimport():
 55     def __init__(self,host):
 56       self.host = host
 57     def run(self):
 58       imp = commands.getstatusoutput('mysql -h %s -uuser -p123456 -S /tmp/mysql.sock< /tmp/sqlquery.sql' % self.host)
 59       self.status = imp[0]
 60       self.msg = imp[1]
 61
 62 class sshcommand():
 63      def __init__(self,host,passwd):
 64        self.host = host
 65        self.passwd = passwd
 66      def run(self):
 67        sc = SSHClient()
 68        sc.load_system_host_keys()
 69        sc._policy = paramiko.AutoAddPolicy()
 70        try:
 71           sc.connect(self.host, 22, 'root', self.passwd ,timeout=5000)
 72           stdin, stdout, stderr, status = sc.call('/data/htdoc/tools/backup.sh')
 73
 74           sc.close()
 75           message = stdout.read()
 76           if status == 0:
 77             logging.info('%s  %s' % (self.host,message))
 78           elif status == 1:
 79             logging.info('%s  %s' % (self.host,message))
 80           elif status == 2:
 81             logging.info('%s  %s' % (self.host,message))
 82           elif status == 3:
 83             logging.info('%s  %s' % (self.host,message))
 84           else:
 85             logging.info('%s  %s' % (self.host,message))
 86        except:
 87           logging.info('%s Connection timed out' % self.host)
 88
 89 class worker(threading.Thread):
 90    def __init__(self,queue):
 91       threading.Thread.__init__(self)
 92       self.queue = queue
 93    def run(self):
 94       while True:
 95         line = self.queue.get()
 96         ipadd,passwd,code_path=line[0],line[1],line[2]
 97         #ipadd,passwd=line[0],line[1]
 98         #print ipadd
 99         sc = sshcommand(ipadd,passwd)
100         sc.run()
101         ry = rsyncThread(ipadd,passwd,code_path)
102         ry.run()
103#         myimport =  mysqlimport(ipadd)
104 #        myimport.run()
105 #        print myimport.status
106 #        status = sc.status
107 #        if status == 0:
108 #          logging.warning(message)
109         self.queue.task_done()
110
111
112 if __name__ == '__main__':
113 # 读取主机列表
114    reader = csv.reader(file('host.txt'))
115 #启用队列函数
116    queue = Queue.Queue()
117    out_queue = Queue.Queue()
118 #开启 5 个线程
119    for i in range(5):
120      t = worker(queue)
121      t.setDaemon(True)
122      t.start()
123 # 把主机列表放入队列
124    for line in reader:
125      queue.put(line)
126    queue.join()
127 #     print "Elapsed Time: %s" % (time.time() - start)
128

host.txt 内容为
# ip passwd web htdoc
192.168.1.2,password,/data/htdoc/

转载请注明:文章转载自:Eric's linux and nginx! (http://www.nginxs.com)
本文地址:http://www.nginxs.com/linux/497.html

分类: linux 标签: , ,
  1. 2018年12月23日08:38 | #1

    The correct advice can prevent money and time.

  2. 2018年12月23日17:07 | #2

    I have read some excellent stuff here. Certainly value
    bookmarking for revisiting. I surprise how so much effort you place to create such a wonderful informative web
    site.

  3. 2018年12月24日00:23 | #3

    If some one desires to be updated with hottest technologies therefore he must be pay a visit this
    website and be up to date daily.

  4. 2018年12月24日08:05 | #4

    The appropriate advice can prevent time and money.

  5. 2018年12月24日08:53 | #5

    Whoa! This blog looks exactly like my old one!
    It’s on a totally different subject but it has pretty much the same page
    layout and design. Great choice of colors!

  6. 2018年12月24日09:44 | #6

    The suitable advice can prevent time and money.

  7. 2018年12月25日06:59 | #7

    The best advice can prevent time and money.

  8. 2018年12月25日11:09 | #8

    The precise advice can prevent money and time.

  9. 2018年12月25日22:11 | #9

    Every weekend i used to pay a visit this site, for the reason that i want enjoyment, for the reason that this
    this web site conations actually nice funny information too.

  10. 2018年12月26日09:03 | #10

    The best recommendation can save you time and
    money.

  11. 2018年12月26日15:41 | #11

    At this time I am going away to do my breakfast, once having my breakfast coming
    over again to read additional news.

  12. 2018年12月28日15:42 | #12

    It’s going to be end of mine day, but before ending
    I am reading this impressive paragraph to increase my knowledge.

  13. 2019年1月2日10:53 | #13

    It’s amazing to go to see this site and reading the
    views of all friends concerning this post, while I am also eager of getting
    know-how.

  14. 2019年1月5日00:03 | #14

    I every time used to study article in news papers but now as I am a user
    of web therefore from now I am using net for posts, thanks to web.

  15. 2019年1月7日08:42 | #15

    Hello There. I found your blog using msn. This
    is an extremely well written article. I will be sure to bookmark it and come back to read more of your useful information. Thanks for the post.
    I will definitely comeback.

  16. 2019年1月8日09:05 | #16

    Hello! Someone in my Facebook group shared this site with us so
    I came to look it over. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers!

    Wonderful blog and fantastic design.

  17. 2019年1月15日23:26 | #17

    Saved as a favorite, I love your blog!

  18. 2019年1月20日11:19 | #18

    It’s the best time to make some plans for the future and it’s time to be happy.
    I’ve read this post and if I could I wish to suggest you
    some interesting things or tips. Maybe you could write next articles referring to this article.
    I desire to read even more things about it!

  19. 2019年1月23日11:18 | #19

    Fabulous, what a blog it is! This blog gives valuable facts to us, keep
    it up.

  20. 2019年1月25日02:55 | #20

    Hi! Would you mind if I share your blog with my zynga group?

    There’s a lot of people that I think would really enjoy your content.
    Please let me know. Thank you

  21. 2019年1月25日11:37 | #21

    What’s up, its pleasant paragraph regarding media print, we
    all be aware of media is a great source of information.

  22. 2019年2月13日08:46 | #22

    With havin so much content and articles do you ever run into
    any problems of plagorism or copyright violation? My site has a lot of completely unique content I’ve either created myself or outsourced but it looks
    like a lot of it is popping it up all over the web without my authorization. Do you know
    any ways to help reduce content from being ripped off?
    I’d genuinely appreciate it.

  23. 2019年2月23日17:21 | #23

    Hi, I do think this is an excellent site. I stumbledupon it ;) I’m going to come back yet again since
    i have bookmarked it. Money and freedom is the greatest way to change, may you
    be rich and continue to guide others.

评论分页
1 ... 8 9 10 497
订阅评论
4+7= (必填)