Python3 Call Salt-api

Source: Internet
Author: User
Tags curl response code

Call Salt-api using Python3
#python3. ximport pycurlfrom io import bytesioimport jsonclass Pycurl (object): Def __init__ (self, URL, **kwargs):         # incoming URL address self.url = URL # Remove header related Information Self.header = Kwargs.get ("header", None) # Create a Curl Object Self.curl = Pycurl.        Curl () # setopt to set some request options # Specify the requested URL self.curl.setopt (Self.curl.URL, Self.url) # set Proxy browser Self.curl.setopt (Self.curl.HEADER, False) # Set Request Mode self.curl.setopt (Self.curl.POST, True) # set HTTPS Way Self.curl.setopt (Pycurl. Ssl_verifypeer, 0) self.curl.setopt (pycurl. Ssl_verifyhost, 0) # Determine if the header exists if Self.header: # set the Analog browser self.curl.setopt (Self.curl .  Httpheader, Self.header) def request (self, Data=none, timeout=none): # Determines if the object type is str if isinstance (data, STR): #将数据提交 self.curl.setopt (Pycurl. Postfields, data) Header_buf = Bytesio () Body_buf = Bytesio () # Forces the acquisition of a new connection, i.e.Connection self.curl.setopt (Self.curl.FRESH_CONNECT, True) in the generation cache # Force disconnects after the interaction is complete, without reusing self.curl.setopt (Self.curl. Forbid_reuse, True) if STR (timeout). IsDigit () and timeout > 0: # Set timeout time-out SELF.CURL.S Etopt (Self.curl.TIMEOUT, TIMEOUT) # directs the returned HTTP header to the callback function Header_buf self.curl.setopt (Self.curl.HEADERFUNCTI        On, Header_buf.write) # directs the returned content to the callback function Body_buf self.curl.setopt (Self.curl.WRITEFUNCTION, Body_buf.write) Try: # Server return information Self.curl.perform () except Pycurl.error:return False # state code Http_code = Self.curl.getinfo (self.curl.HTTP_CODE) # Close Connection self.curl.close () # Return status code header Body return {"Http_code": Http_code, "header": Header_buf.getvalue (), "Body": Body_buf.getvalue (), "url": Self.url}        Class Saltapi (object): Def __init__ (Self,**kwargs): # set timeout time self.timeout = kwargs.get ("timeout", 300) # Set Header information self. Header = Kwargs.get ("header", ["Content-type:application/json"]) # gets the URL Self.__url = "https://192.168.104. 76:8,000 "# Get self.__username =" Salt-api "Self.__password =" Salt-api "# token ID get def token _ID (self): obj = {' Eauth ': ' Pam ', ' username ': self.__username, ' Password ': self.__password} result = Self.po            St (prefix= "/login", **obj) if result:try:self.__token_id = result[' return '][0][' token '] Except Keyerror:raise keyerror print (self.__token_id) return self.__token_id D EF post (self, prefix= "/", Token=none,**data): # URL Stitching url = self.__url + prefix print (data) # Instantiation Self.header.append (token) curl = Pycurl (URL, header=self.header) # Originating Request result = Curl . Request (Data=json.dumps (data), timeout=self.timeout) # judgment value if not result:return result # Determine if the status code is equal toesult["Http_code"]! = 200:self.response = "Response code%s". Format (result["info" ["Http_code"]) re  Turn self.response result = Json.loads (result["Body"].decode ()) # Determines if there is an error if "error" in result and result["Error"]: Self.response = "%s"% (result["error" ["Data"], result["error" ["Code"]) Retu        RN Self.response #返回正确的数据 return result def all_key (self): ' Get all Minion_key ' token = ' x-auth-token:%s '%self.token_id () obj = {' Client ': ' Wheel ', ' fun ': ' key.list_all '} content = S Elf.post (token=token,**obj) # Remove authentication passed minions = content[' return '][0][' data ' [' return '] [' Minions '] #  Print (' Certified ', Minions) # Remove unauthenticated minions_pre = content[' return '][0][' data ' [' return '] [' Minions_pre '] # Print (' unauthenticated ', Minions_pre) return Minions,minions_pre def accept_key (self,node_name): ' If you want to authenticate a master    Call this method '    token = ' x-auth-token:%s '% self.token_id () obj = {' Client ': ' Wheel ', ' fun ': ' key.accept ', ' Match ': Node_name}        Content = Self.post (token=token,**obj) print (content) ret = content[' return '][0][' data ' [' success '] return RET # Remove authentication method def delete_key (self, node_name): obj = {' Client ': ' Wheel ', ' fun ': ' Key.delete ', ' mat Ch ': node_name} token = ' x-auth-token:%s '% self.token_id () content = Self.post (Token=token, **obj) r        ET = content[' return '][0][' data ' [' success '] return RET # for host remote execution Module def host_remote_func (self, TGT, fun): "The TGT is host fun is module write on module name return can be used to invoke basic assets such as Curl-k HTTPS://IP address: 8080/>-H" acce Pt:application/x-yaml ">-H" x-auth-token:b50e90485615309de0d83132cece2906f6193e43 ">-D client= ' Local ' >-D tgt= ' * ' >-D fun= ' test.ping ' module to execute return:-Iz28r91y6 6hz:true Node2. minion:true ' obj = {' client ': ' Local ', ' TGT ': TGT, ' fun ': fun} token = ' x-auth-token:%s ' percent self. token_id () content = Self.post (Token=token, **obj) ret = content[' return '][0] return ret def group  _remote_func (self,tgt,fun): obj = {' client ': ' Local ', ' TGT ': TGT, ' fun ': fun, ' expr_form ': ' Nodegroup '} token = ' x-auth-token:%s '% self.token_id () content = Self.post (Token=token, **obj) print (content) ret =        content[' return '][0] return ret def host_remote_execution_module (self,tgt,fun,arg): ' Execute fun incoming parameter arg '        obj = {' client ': ' Local ', ' TGT ': TGT, ' fun ': fun, ' arg ': arg} token = ' x-auth-token:%s '% self.token_id () Content = Self.post (Token=token, **obj) ret = content[' return '][0] return ret #print (salt_aa.host_r Emote_execution_module (' * ', ' cmd.run ', ' Ifconfig ') # performs DEF Group_remote_execution_module based on grouping (self, TGT, fun, ARG) : "' According to groupTo execute the TGT = ' obj = {' client ': ' Local ', ' TGT ': TGT, ' fun ': fun, ' arg ': arg, ' expr_form ': ' Nodegroup '} token = ' x-auth-token:%s '% self.token_id () content = Self.post (Token=token, **obj) Jid = content[' r  Eturn '][0] return Jid def host_sls (self, TGT, arg): ' Host to SLS ' ' obj = {' client ': ' Local ', ' TGT ': TGT, ' fun ': ' State.sls ', ' arg ': arg} token = ' x-auth-token:%s '% self.token_id () content = Self.post (token= token, **obj) return content def Group_sls (self, TGT, arg): ' ' Group for SLS ' ' obj = {' client ': ' Loca L ', ' TGT ': TGT, ' fun ': ' State.sls ', ' arg ': arg, ' expr_form ': ' nodegroup '} token = ' x-auth-token:%s '% self.token_id () content = Self.post (Token=token, **obj) Jid = content[' return '][0][' Jid '] return Jid def host_s Ls_async (self, TGT, arg): ' Host asynchronous SLS ' ' obj = {' client ': ' Local_async ', ' TGT ': TGT, ' fun ': ' State.sls ', ' AR G ': arg} token =' x-auth-token:%s '% self.token_id () content = Self.post (Token=token, **obj) Jid = content[' return '][0][' Jid ' ] Return Jid def group_sls_async (self, TGT, arg): ' ' Group asynchronous SLS ' ' obj = {' client ': ' Local_async ', '        TGT ': TGT, ' fun ': ' State.sls ', ' arg ': arg, ' expr_form ': ' nodegroup '} token = ' x-auth-token:%s '% self.token_id () Content = Self.post (Token=token, **obj) Jid = content[' return '][0][' Jid '] return Jid def Server_grou P_pillar (self, TGT, ARG, **kwargs): "' Grouping for SLS and pillar '" obj = {' client ': ' Local ', ' TGT ': TGT, ' fun ': ' s Tate.sls ', ' arg ': arg, ' expr_form ': ' Nodegroup ', ' Kwarg ': kwargs} token = ' x-auth-token:%s '% self.to ken_id () content = Self.post (Token=token, **obj) Jid = content[' return '][0] Print (JID) def server _hosts_pillar (self, TGT, Arg,**kwargs): "" Executes SLS and pillar for the host "obj = {" Client ":" Local "," TGT ": TGT," f Un ":" State.sls "," Arg ": ARG, "Kwarg": Kwargs} token = ' x-auth-token:%s '% self.token_id () content = Self.post (Token=token, **obj) Jid = content[' return '][0] return Jid def jobs_all_list (self): ' Print all Jid cache ' ' token = ' X-auth -token:%s '% self.token_id () obj = {"Client": "Runner", "Fun": "jobs.list_jobs"} content = Self.post (token=t Oken, **obj) print (content) def jobs_jid_status (self, Jid): ' View Jid run status ' ' token = ' X-auth-token :%s '% self.token_id () obj = {"Client": "Runner", "Fun": "Jobs.lookup_jid", "Jid": jid} content = Self.post ( Token=token, **obj) print (content) return contentif __name__ = = ' __main__ ': sa = saltapi.   Saltapi () Print (Sa.host_remote_execution_module (' node76 ', ' cmd.run ', ' ifconfig ')) Print (Sa.accept_key ("node76"))

Python3 Call Salt-api

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.