esdghj 发表于 2014-7-25 09:28:42

tornado+ansible+twisted+mongodb运维自动化系统开发(二)

源码:

    #!/usr/bin/env python
    #coding:utf-8
    import os.path
    import tornado.locale
    import tornado.httpserver
    import tornado.ioloop
    import tornado.options
    import tornado.web
    from tornado.options import define, options
    import pymongo
      
    define("port", default=8000, help="run on the given port", type=int)
      
    class Application(tornado.web.Application):
      def __init__(self):
            #初始化一些东西
            handlers = [
                #url匹配
                (r"/", MainHandler),
                (r"/index.html", MainHandler),
                (r"/add.html", AddHandler),
                (r"/listhost.html",List_hostHandler),
                (r"/delete.html", delete_hostHandler),
                (r"/module_action.html", Module_actionHandler),
      
            ]
            settings = dict(
                #程序设置,字典形式
                template_path=os.path.join(os.path.dirname(__file__), "templates"),
                #设置模板文件路径
                static_path=os.path.join(os.path.dirname(__file__), "static"),
                #设置静态文件路径,如css\jpg\gif等
                # ui_modules={"Book": BookModule},
                #设置ui模块,可以用字典添加多个
                debug=True,
            )
            conn = pymongo.Connection("localhost", 27017)
            #初始化数据库连接
            self.db = conn["waitfish"]
            #选择mongodb集合
            tornado.web.Application.__init__(self, handlers, **settings)
            #传入设置配置
      
    class MainHandler(tornado.web.RequestHandler):
      #主页函数方法
      def get(self):
            #设置httpget方法函数
            self.render(
                "index.html",
            )
      
      
    class AddHandler(tornado.web.RequestHandler):
      #添加主机页面
      def get(self):
            self.render(
                "add.html",
            )
      
      
      
      
    class List_hostHandler(tornado.web.RequestHandler):
      #主机列表页面,get方式现实全部主机
      def get(self, *args, **kwargs):
            coll = self.application.db.waitfish
            hosts = coll.find()
            self.render(
                "listhost.html",
                hosts = hosts
            )
      
      def post(self):
            #post方法现实post的主机
            coll = self.application.db.waitfish
            #初始化数据库连接
            hostname = self.get_argument('hostname')
            #从post中获取主机名
            ipadd = self.get_argument('ipadd')
            #获取主机ip地址
            username = self.get_argument('username')
            #获取主机用户名
            password = self.get_argument('password')
            #获取密码
            post_dic = {'hostname':hostname, 'ipadd':ipadd, 'username':username, 'password':password}
            #生成要存入数据库的内容
            hosts = coll.find({'hostname':hostname})
            #根据主机名判断是否已经存在该主机
            if hosts:
                #如果不存在
                import ansible.runner
                #对主机进行初始化,复制公钥到受管主机,(添加ip地址和主机名对到本机的hosts文件和ansible的hosts文件)
                runner_copy_autherized_keys = ansible.runner.Runner(
                        module_name = 'copy',
                        module_args = "src=~/.ssh/id_rsa.pubdest=~/.ssh/authorized_keys owner=%s group=%s mode=644 backup=yes" %(username, username),
                        remote_user = username,
                        remote_pass = password,
                        sudo = 'yes',
                        sudo_pass =password,
                        pattern = hostname,
                )
                b = runner_copy_autherized_keys.run()
                print b
      
                runner = ansible.runner.Runner(
                  module_name = 'shell',
                  module_args = "echo '%s' >>/etc/ansible/hosts"% ipadd,
                  sudo = 'yes',
                  sudo_pass = 'xxxxxxx',
                  transport = 'local',
                  pattern = '127.0.0.1',
                )
                #异步执行该操作,防止web页面被卡住
                runner.run_async(30)
                coll.save(post_dic)
                #保存主机信息到数据库
                self.render(
                "listhost.html",
                #调用主机列表模板显示被添加的主机信息
                hosts = hosts,
            )
            else:
                #如果存在,则更新主机信息
                coll.update(post_dic,post_dic)
                self.render(
                # "listhost.html",
                # hosts = hosts,
            )
      
      
    class delete_hostHandler(tornado.web.RequestHandler):
      #定义删除主机的函数
      def post(self, *args, **kwargs):
            hostnames = self.get_arguments('hostname')
            # 根据checkbox得到hostname的列表
            coll = self.application.db.waitfish
            #获得数据库游标
            for host in hostnames:
                coll.remove({"hostname":host})
                #根据主机名删除
            self.render(
                "delete_info.html",
                message = "%s is removed!"% hostnames,
                #给出消息
            )
      
      
    class Module_actionHandler(tornado.web.RequestHandler):
      #定义模块操作函数方法
      def get(self, *args, **kwargs):
            coll = self.application.db.waitfish
            #初始化数据库连接
            hosts = coll.find({}, {'hostname':1,'ipadd':1,"_id":0})
            #这里hostname:1 表示返回hostname列,由于_id列每次都返回所以用0禁用掉,模板还可以一样
            modulenames = ['ping', 'setup', 'copy','shell']
            #现实我们定义的操作
            self.render(
                "module_action.html",
                hosts = hosts,
                modulenames = modulenames,
            )
      
      def post(self, *args, **kwargs):
            ipadd = self.get_arguments('ipadd')
            #获取主机名
            module = self.get_arguments('modulename')
            #获取模块名
            arg = self.get_arguments('args')
            #获取参数
            coll = self.application.db.waitfish
            #初始化数据库
            user = coll.find_one({'ipadd':'%s'%ipadd})['username']
            hostname = coll.find_one({'ipadd':'%s'%ipadd})['hostname']
            #从数据库找到主机的用户名信息
            import ansible.runner
            runner = ansible.runner.Runner(
                #根据ansible的api来运行脚本
                module_name = module,
                module_args = arg,
                remote_user = user,
                #设定操作远程受管主机的用户名
                pattern = ipadd,
                #设定要操作主机名
            )
            result = runner.run()
            #得到返回结果,这里是同步执行,下个版本改进异步
            def pars_result(result):
                # 定义一个判断结果的函数
                if len(result['dark'])>0:
                  # dark返回不为空则表示操作失败了
                  return result['dark'],'失败!'
                else:
                  return result['contacted'],'成功!'
            result = pars_result(result)
            self.render(
                "message.html",
                hostname = hostname,
                message = result,
                jieguo = result
            )
      
    if __name__ == "__main__":
      tornado.options.parse_command_line()
      http_server = tornado.httpserver.HTTPServer(Application())
      http_server.listen(options.port)
      tornado.ioloop.IOLoop.instance().start()

页: [1]
查看完整版本: tornado+ansible+twisted+mongodb运维自动化系统开发(二)