Tornado + ansible + twisted + automatic system development for mongodb O & M (2)

Source: Internet
Author: User

Tornado + ansible + twisted + automatic system development for mongodb O & M (2)

Source code:

#! /Usr/bin/env python # coding: utf-8import OS. pathimport tornado. localeimport tornado. httpserverimport tornado. ioloopimport tornado. optionsimport tornado. webfrom tornado. options import define, optionsimport py1_define ("port", default = 8000, help = "run on the given port", type = int) class Application (tornado. web. application): def _ init _ (self): # initialize some things handlers = [# url matching (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 (# program settings, Dictionary form template_path = OS. path. join (OS. path. dirname (_ file _), "templates"), # Set the template file path static_path = OS. path. join (OS. path. dirname (_ file _), "static"), # Set static file paths, such as css \ jpg \ gif # ui_modules = {"Book": BookModu Le}, # Set the ui module. You can use the dictionary to add multiple debug = True,) conn = pymongo. connection ("localhost", 27017) # initialize the database Connection self. db = conn ["waitfish"] # select the tornado set of mongodb. web. application. _ init _ (self, handlers, ** settings) # input settings to configure class MainHandler (tornado. web. requestHandler): # homepage Function Method def get (self): # sets the HTTP get function self. render ("index.html",) class AddHandler (tornado. web. requestHandler): # Add the host page def get (self): self. render ("add. Html ",) class List_hostHandler (tornado. web. requestHandler): # host list page. In the get mode, all hosts are def get (self, * args, ** kwargs): coll = self. application. db. waitfish hosts = coll. find () self. render ("listhost.html", hosts = hosts) def post (self): # post method real post host coll = self. application. db. waitfish # initialize the database connection hostname = self. get_argument ('hostname') # obtain the host name ipadd = self from post. get_argument ('ipadd') # obtain the Host IP address usernam E = self. get_argument ('username') # obtain the host username password = self. get_argument ('Password') # obtain the password post_dic = {'hostname': hostname, 'ipadd': ipadd, 'username': username, 'Password ': password} # generate the content hosts = coll. find ({'hostname': hostname}) # determine whether the host already exists based on the host name if hosts: # if the host does not exist, import ansible. runner # initializes the host and copies the public key to the managed host. (add the IP address and host name to the host's hosts file and ansible's hosts file) runner_copy_autherized_keys = ansible. runner. run Ner (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_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 = '1970. 127. 0.0.1 ',) # run this operation asynchronously to prevent the web page from getting stuck. run_async (30) coll. save (post_dic) # save host information to the database self. render ("listhost.html", # Call the host list template to display the added host information hosts = hosts,) else: # If yes, update the host information coll. update (post_dic, post_dic) self. render (# "listhost.html", # hosts = hosts,) class delete_hostHandler (tornado. web. requestHandler): # define the def post (self, * args, ** kwargs) function for deleting a host: hostnames = self. get_arguments ('ho Stname') # obtain the hostname list coll = self according to the checkbox. application. db. waitfish # obtain the database cursor for host in hostnames: coll. remove ({"hostname": host}) # delete self based on the host name. render ("delete_info.html", message = "% s is removed! "% Hostnames, # message) class Module_actionHandler (tornado. web. requestHandler): # define the module operation function method def get (self, * args, ** kwargs): coll = self. application. db. waitfish # initialize the database connection hosts = coll. find ({}, {'hostname': 1, 'ipadd': 1, "_ id": 0}) # Here hostname: 1 indicates that the hostname column is returned, because the _ id column is returned every time, 0 is disabled. The template can also be the same as modulenames = ['ping', 'setup', 'copy ', 'shell'] # the actual operation we define is self. render ("module_action.html", hosts = hosts, modulenames = Modulenames,) def post (self, * args, ** kwargs): ipadd = self. get_arguments ('ipadd') [0] # obtain the host name module = self. get_arguments ('modulename') [0] # obtain the module name arg = self. get_arguments ('args') [0] # obtain the coll = self. application. db. waitfish # initialize database user = coll. find_one ({'ipadd': '% s' % ipadd}) ['username'] hostname = coll. find_one ({'ipadd': '% s' % ipadd}) ['hostname'] # Find the host username from the database and import ansible. runner = ansible. Runner. runner (# Run the script module_name = module, module_args = arg, remote_user = user according to the ansible api, # Set the user name pattern = ipadd for remotely managed hosts, # Set the host name to be operated.) result = runner. run () # Get the returned result. Here the result is synchronously executed. In the next version, the asynchronous def pars_result (result) is improved ): # define a function for determining the result if len (result ['dark'])> 0: # if the result returned by dark is not null, the return result ['dark'] fails. 'failed! 'Else: return result ['contacted'], 'success! 'Result = pars_result (result) self. render ("message.html", hostname = hostname, message = 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 ()

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.