Development of TORNADO+ANSIBLE+TWISTED+MONGODB operation and maintenance Automation system (II.)

Source: Internet
Author: User

Source:

#!/usr/bin/env python#coding:utf-8import os.pathimport Tornado.localeimport tornado.httpserverimport Tornado.ioloopimport tornado.optionsimport tornado.webfrom tornado.options Import define, Optionsimport Pymongodefine ("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", M Ainhandler), (R "/add.html", AddHandler), (R "/listhost.html", List_hosthandler), (r "/delete            . html ", Delete_hosthandler), (R"/module_action.html ", Module_actionhandler),] settings = Dict (            #程序设置, dictionary form template_path=os.path.join (Os.path.dirname (__file__), "Templates"), #设置模板文件路径 Static_path=os.path.join (Os.path.dirname (__file__), "Static"), #设置静态文件路径, such as css\jpg\gif etc # u i_modules={"book": Bookmodule}, #设置ui模块, you can add multiple debug=true in a dictionary,) conn = Pymongo. Connection ("localhost", 27017) #初始化数据库连接 self.db = conn["Waitfish"] #选择mongodb集合 TORNADO.WEB.A    Pplication.__init__ (self, handlers, **settings) #传入设置配置class MainHandler (tornado.web.RequestHandler): #主页函数方法 def get (self): #设置httpget方法函数 self.render ("index.html",) class AddHandler (tornado.web.Re Questhandler): #添加主机页面 def get (self): Self.render ("add.html",) class List_hosthandler (torn Ado.web.RequestHandler): #主机列表页面, get mode reality all host Def get (self, *args, **kwargs): coll = self.application.db.waitf Ish hosts = Coll.find () self.render ("listhost.html", hosts = hosts) def PO St (self): #post方法现实post的主机 coll = self.application.db.waitfish #初始化数据库连接 hostname = self.get_a Rgument (' hostname ') #从post中获取主机名 Ipadd = self.get_argument (' Ipadd ')        #获取主机ip地址 username = self.get_argument (' username ') #获取主机用户名 password = self.get_argument (' pas        Sword ') #获取密码 post_dic = {' hostname ': hostname, ' ipadd ': Ipadd, ' username ': username, ' password ':p assword} #生成要存入数据库的内容 hosts = Coll.find ({' hostname ': hostname}) #根据主机名判断是否已经存在该主机 if hosts: #如果不存 In the import Ansible.runner #对主机进行初始化, copy the public key to the managed host, (add IP address and hostname to native Hosts file and ansible Hosts file) Runn  Er_copy_autherized_keys = Ansible.runner.Runner (module_name = ' Copy ', Module_args =                    "Src=~/.ssh/id_rsa.pub Dest=~/.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_ke Ys.run () PrinT B Runner = Ansible.runner.Runner (module_name = ' shell ', Module_args = ' echo '% S ' >>/etc/ansible/hosts "% ipadd, sudo = ' yes ', Sudo_pass = ' xxxxxxx ', T Ransport = ' local ', pattern = ' 127.0.0.1 ',) #异步执行该操作 to prevent the Web page from being stuck runner.ru            N_async (Coll.save) (post_dic) #保存主机信息到数据库 self.render ("listhost.html", #调用主机列表模板显示被添加的主机信息 hosts = hosts,) Else: #如果存在, update host information 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_ar  Guments (' hostname ') # Gets the list of hostname according to the checkbox coll = self.application.db.waitfish #获得数据库游标 for     Host in hostnames:       Coll.remove ({"hostname": host}) #根据主机名删除 Self.render ("delete_info.html", Me Ssage = "%s is removed!" % hostnames, #给出消息) class Module_actionhandler (Tornado.web.RequestHandler): #定义模块操作函数方法 def get (SE LF, *args, **kwargs): coll = self.application.db.waitfish #初始化数据库连接 hosts = Coll.find ({}, {' hostname ' : 1, ' Ipadd ': 1, "_id": 0}) #这里hostname: 1 means that the hostname column is returned, because the _id column is returned every time, the template can also be as Modulenames = [' ping ', ' setup '            , ' Copy ', ' Shell '] #现实我们定义的操作 self.render ("module_action.html", hosts = hosts,        Modulenames = Modulenames,) def post (self, *args, **kwargs): Ipadd = self.get_arguments (' ipadd ') [0]         #获取主机名 module = self.get_arguments (' modulename ') [0] #获取模块名 arg = self.get_arguments (' args ') [0] #获取参数 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, #设定要操作 Hostname) result = Runner.run () #得到返回结果, here is synchronous execution, next version improved Async def pars_result (Result): # defines a The function If Len (result[' Dark ') >0: # Dark return NOT NULL indicates that the operation failed with return result[' dark '], '            Failed! '        Else:return result[' contacted '], ' success! ' result = Pars_result (result) Self.render ("message.html", hostname = hostname, MES     Sage = result[0], Jieguo = result[1]) If __name__ = = "__main__": Tornado.options.parse_command_line () Http_server = Tornado.httpserver.HTTPServer (Application ()) httP_server.listen (Options.port) tornado.ioloop.IOLoop.instance (). Start () 


Development of TORNADO+ANSIBLE+TWISTED+MONGODB operation and maintenance Automation system (II.)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.