首页 > 代码库 > tornado+ansible+twisted+mongodb运维自动化系统开发(二)

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=http://www.mamicode.com/~/.ssh/id_rsa.pub  dest=~/.ssh/authorized_keys owner=%s group=%s mode=644 backup=yes" %(username, username),>

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