Advertisement
Guest User

xmlsh.py

a guest
Nov 22nd, 2011
461
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 26.74 KB | None | 0 0
  1. #!/usr/bin/python
  2. # Script created by Isox 18.11.2011
  3. # Update 21.11.2011 : Added etree lib for preserver attributes order.
  4. # Update 22.11.2011 : Removed minidom. All parsing made on etree. Added "add", "settext" commands. Improved "cd".
  5. #
  6. # This XMLsh utility will help you to agregate state.db file
  7. # With best regards.
  8. from subprocess import call
  9. try:
  10.     import xml.etree.ElementTree as etree
  11. except:
  12.     import elementtree.ElementTree as etree
  13. import sys
  14. ver=list(sys.version.split())[0]
  15. try:
  16.     from thread import get_ident as _get_ident
  17. except:
  18.     from collections import OrderedDict as odict
  19. else:
  20.     class _Nil(object):
  21.         def __repr__(self):
  22.             return "nil"
  23.  
  24.         def __eq__(self, other):
  25.             if (isinstance(other, _Nil)):
  26.                 return True
  27.             else:
  28.                 return NotImplemented
  29.  
  30.         def __ne__(self, other):
  31.             if (isinstance(other, _Nil)):
  32.                 return False
  33.             else:
  34.                 return NotImplemented
  35.  
  36.     _nil = _Nil()
  37.  
  38.     class _odict(object):
  39.         def _dict_impl(self):
  40.             return None
  41.  
  42.         def __init__(self, data=(), **kwds):
  43.             if kwds:
  44.                 raise TypeError(" ")
  45.             self._dict_impl().__init__(self)
  46.         # If you give a normal dict, then the order of elements is undefined
  47.             if hasattr(data, "iteritems"):
  48.                 for key, val in data.iteritems():
  49.                     self[key] = val
  50.             else:
  51.                 for key, val in data:
  52.                     self[key] = val
  53.  
  54.         # Double-linked list header
  55.         def _get_lh(self):
  56.             dict_impl = self._dict_impl()
  57.             if not hasattr(self, '_lh'):
  58.                 dict_impl.__setattr__(self, '_lh', _nil)
  59.             return dict_impl.__getattribute__(self, '_lh')
  60.  
  61.         def _set_lh(self, val):
  62.             self._dict_impl().__setattr__(self, '_lh', val)
  63.  
  64.         lh = property(_get_lh, _set_lh)
  65.  
  66.         # Double-linked list tail
  67.         def _get_lt(self):
  68.             dict_impl = self._dict_impl()
  69.             if not hasattr(self, '_lt'):
  70.                 dict_impl.__setattr__(self, '_lt', _nil)
  71.             return dict_impl.__getattribute__(self, '_lt')
  72.  
  73.         def _set_lt(self, val):
  74.             self._dict_impl().__setattr__(self, '_lt', val)
  75.  
  76.         lt = property(_get_lt, _set_lt)
  77.  
  78.         def __getitem__(self, key):
  79.             return self._dict_impl().__getitem__(self, key)[1]
  80.  
  81.         def __setitem__(self, key, val):
  82.             dict_impl = self._dict_impl()
  83.             try:
  84.                 dict_impl.__getitem__(self, key)[1] = val
  85.             except KeyError:
  86.                 new = [dict_impl.__getattribute__(self, 'lt'), val, _nil]
  87.                 dict_impl.__setitem__(self, key, new)
  88.                 if dict_impl.__getattribute__(self, 'lt') == _nil:
  89.                     dict_impl.__setattr__(self, 'lh', key)
  90.                 else:
  91.                     dict_impl.__getitem__(
  92.                         self, dict_impl.__getattribute__(self, 'lt'))[2] = key
  93.                 dict_impl.__setattr__(self, 'lt', key)
  94.  
  95.         def __delitem__(self, key):
  96.             dict_impl = self._dict_impl()
  97.             pred, _ ,succ= self._dict_impl().__getitem__(self, key)
  98.             if pred == _nil:
  99.                 dict_impl.__setattr__(self, 'lh', succ)
  100.             else:
  101.                 dict_impl.__getitem__(self, pred)[2] = succ
  102.             if succ == _nil:
  103.                 dict_impl.__setattr__(self, 'lt', pred)
  104.             else:
  105.                 dict_impl.__getitem__(self, succ)[0] = pred
  106.             dict_impl.__delitem__(self, key)
  107.  
  108.         def __contains__(self, key):
  109.             # XXX: try: self[key] ...
  110.             return key in self.keys()
  111.  
  112.         def has_key(self, key):
  113.             return key in self
  114.  
  115.         def __len__(self):
  116.             return len(self.keys())
  117.  
  118.         def __str__(self):
  119.             pairs = ("%r: %r" % (k, v) for k, v in self.iteritems())
  120.             return "{%s}" % ", ".join(pairs)
  121.  
  122.         def __repr__(self):
  123.             if self:
  124.                 pairs = ("(%r, %r)" % (k, v) for k, v in self.iteritems())
  125.                 return "odict([%s])" % ", ".join(pairs)
  126.             else:
  127.                 return "odict()"
  128.  
  129.         def get(self, k, x=None):
  130.             if k in self:
  131.                 return self._dict_impl().__getitem__(self, k)[1]
  132.             else:
  133.                 return x
  134.  
  135.         def __iter__(self):
  136.             dict_impl = self._dict_impl()
  137.             curr_key = dict_impl.__getattribute__(self, 'lh')
  138.             while curr_key != _nil:
  139.                 yield curr_key
  140.                 curr_key = dict_impl.__getitem__(self, curr_key)[2]
  141.  
  142.         iterkeys = __iter__
  143.  
  144.         def keys(self):
  145.             return list(self.iterkeys())
  146.  
  147.         def itervalues(self):
  148.             dict_impl = self._dict_impl()
  149.             curr_key = dict_impl.__getattribute__(self, 'lh')
  150.             while curr_key != _nil:
  151.                 _, val, curr_key = dict_impl.__getitem__(self, curr_key)
  152.                 yield val
  153.  
  154.         def values(self):
  155.             return list(self.itervalues())
  156.  
  157.         def iteritems(self):
  158.             dict_impl = self._dict_impl()
  159.             curr_key = dict_impl.__getattribute__(self, 'lh')
  160.             while curr_key != _nil:
  161.                 _, val, next_key = dict_impl.__getitem__(self, curr_key)
  162.                 yield curr_key, val
  163.                 curr_key = next_key
  164.  
  165.         def items(self):
  166.             return list(self.iteritems())
  167.  
  168.         def sort(self, cmp=None, key=None, reverse=False):
  169.             items = [(k, v) for k,v in self.items()]
  170.             if cmp is not None:
  171.                 items = sorted(items, cmp=cmp)
  172.             elif key is not None:
  173.                 items = sorted(items, key=key)
  174.             else:
  175.                 items = sorted(items, key=lambda x: x[1])
  176.             if reverse:
  177.                 items.reverse()
  178.             self.clear()
  179.             self.__init__(items)
  180.  
  181.         def clear(self):
  182.             dict_impl = self._dict_impl()
  183.             dict_impl.clear(self)
  184.             dict_impl.__setattr__(self, 'lh', _nil)
  185.             dict_impl.__setattr__(self, 'lt', _nil)
  186.  
  187.         def copy(self):
  188.             return self.__class__(self)
  189.  
  190.         def update(self, data=(), **kwds):
  191.             if kwds:
  192.                 raise TypeError("update() of ordered dict takes no keyword "
  193.                                 "arguments to avoid an ordering trap.")
  194.             if hasattr(data, "iteritems"):
  195.                 data = data.iteritems()
  196.             for key, val in data:
  197.                 self[key] = val
  198.  
  199.         def setdefault(self, k, x=None):
  200.             try:
  201.                 return self[k]
  202.             except KeyError:
  203.                 self[k] = x
  204.                 return x
  205.  
  206.         def pop(self, k, x=_nil):
  207.             try:
  208.                 val = self[k]
  209.                 del self[k]
  210.                 return val
  211.             except KeyError:
  212.                 if x == _nil:
  213.                     raise
  214.                 return x
  215.  
  216.         def popitem(self):
  217.             try:
  218.                 dict_impl = self._dict_impl()
  219.                 key = dict_impl.__getattribute__(self, 'lt')
  220.                 return key, self.pop(key)
  221.             except KeyError:
  222.                 raise KeyError("'popitem(): ordered dictionary is empty'")
  223.  
  224.         def riterkeys(self):
  225.             """To iterate on keys in reversed order.
  226.            """
  227.             dict_impl = self._dict_impl()
  228.             curr_key = dict_impl.__getattribute__(self, 'lt')
  229.             while curr_key != _nil:
  230.                 yield curr_key
  231.                 curr_key = dict_impl.__getitem__(self, curr_key)[0]
  232.  
  233.         __reversed__ = riterkeys
  234.  
  235.         def rkeys(self):
  236.             """List of the keys in reversed order.
  237.            """
  238.             return list(self.riterkeys())
  239.  
  240.         def ritervalues(self):
  241.             """To iterate on values in reversed order.
  242.            """
  243.             dict_impl = self._dict_impl()
  244.             curr_key = dict_impl.__getattribute__(self, 'lt')
  245.             while curr_key != _nil:
  246.                 curr_key, val, _ = dict_impl.__getitem__(self, curr_key)
  247.                 yield val
  248.  
  249.         def rvalues(self):
  250.             """List of the values in reversed order.
  251.            """
  252.             return list(self.ritervalues())
  253.  
  254.         def riteritems(self):
  255.             """To iterate on (key, value) in reversed order.
  256.            """
  257.             dict_impl = self._dict_impl()
  258.             curr_key = dict_impl.__getattribute__(self, 'lt')
  259.             while curr_key != _nil:
  260.                 pred_key, val, _ = dict_impl.__getitem__(self, curr_key)
  261.                 yield curr_key, val
  262.                 curr_key = pred_key
  263.  
  264.         def ritems(self):
  265.             """List of the (key, value) in reversed order.
  266.            """
  267.             return list(self.riteritems())
  268.  
  269.         def firstkey(self):
  270.             if self:
  271.                 return self._dict_impl().__getattribute__(self, 'lh')
  272.             else:
  273.                 raise KeyError("'firstkey(): ordered dictionary is empty'")
  274.  
  275.         def lastkey(self):
  276.             if self:
  277.                 return self._dict_impl().__getattribute__(self, 'lt')
  278.             else:
  279.                 raise KeyError("'lastkey(): ordered dictionary is empty'")
  280.  
  281.         def as_dict(self):
  282.             return self._dict_impl()(self.items())
  283.  
  284.         def _repr(self):
  285.             """_repr(): low level repr of the whole data contained in the odict.
  286.            Useful for debugging.
  287.            """
  288.             dict_impl = self._dict_impl()
  289.             form = "odict low level repr lh,lt,data: %r, %r, %s"
  290.             return form % (dict_impl.__getattribute__(self, 'lh'),
  291.                            dict_impl.__getattribute__(self, 'lt'),
  292.                            dict_impl.__repr__(self))
  293.  
  294.     class odict(_odict, dict):
  295.         def _dict_impl(self):
  296.             return dict
  297.  
  298. if(ver[0]=="3"):
  299. #Ordered atributes tree building for Python 3
  300.     def _start_list(self, tag, attrib_in):
  301.         fixname = self._fixname
  302.         tag = fixname(tag)
  303.         attrib=odict()
  304.         if attrib_in:
  305.             for i in range(0, len(attrib_in), 2):
  306.                 attrib[fixname(attrib_in[i])] = attrib_in[i+1]
  307.         return self.target.start(tag, attrib)
  308. #Replace base function with mine
  309.     etree.XMLTreeBuilder._start_list = _start_list
  310. if(ver[0]=="2"):
  311. #Ordered atributes tree building for Python 2.4
  312.     def _start(self, tag, attrib_in):
  313.         fixname = self._fixname
  314.         tag = fixname(tag)
  315.         attrib = odict()
  316.         for key, value in attrib_in.items():
  317.             attrib[fixname(key)] = self._fixtext(value)
  318.         return self._target.start(tag, attrib)
  319.    
  320.     def _start_list(self, tag, attrib_in):
  321.         fixname = self._fixname
  322.         tag = fixname(tag)
  323.         attrib = odict()
  324.         if attrib_in:
  325.             for i in range(0, len(attrib_in), 2):
  326.                 attrib[fixname(attrib_in[i])] = attrib_in[i+1]
  327.         return self._target.start(tag, attrib)
  328. #Replace base function with mine
  329.     etree.XMLTreeBuilder._start_list = _start_list
  330.     etree.XMLTreeBuilder._strt = _start
  331. if(ver[0]=="3"):
  332. #Ordered serializer....let's try =)
  333.     def _serialize_xml(write, elem, qnames, namespaces):
  334.         tag = elem.tag
  335.         text = elem.text
  336.         if tag is etree.Comment:
  337.             write("<!--%s-->" % text)
  338.         elif tag is etree.ProcessingInstruction:
  339.             write("<?%s?>" % text)
  340.         else:
  341.             tag = qnames[tag]
  342.             if tag is None:
  343.                 if text:
  344.                     write(etree._escape_cdata(text))
  345.                 for e in elem:
  346.                     etree._serialize_xml(write, e, qnames, None)
  347.             else:
  348.                 write("<" + tag)
  349.                 items = list(elem.items())
  350.                 if items or namespaces:
  351.                     if namespaces:
  352.                         for v, k in sorted(namespaces.items(),
  353.                                            key=lambda x: x[1]):  # sort on prefix
  354.                             if k:
  355.                                 k = ":" + k
  356.                             write(" xmlns%s=\"%s\"" % (
  357.                                 k,
  358.                                 etree._escape_attrib(v)
  359.                                 ))
  360.                     for k, v in list(items):  # no !!!! lexical order
  361.                         if isinstance(k, etree.QName):
  362.                             k = k.text
  363.                         if isinstance(v, etree.QName):
  364.                             v = qnames[v.text]
  365.                         else:
  366.                             v = etree._escape_attrib(v)
  367.                         write(" %s=\"%s\"" % (qnames[k], v))
  368.                 if text or len(elem):
  369.                     write(">")
  370.                     if text:
  371.                         write(etree._escape_cdata(text))
  372.                     for e in elem:
  373.                         etree._serialize_xml(write, e, qnames, None)
  374.                     write("</" + tag + ">")
  375.                 else:
  376.                     write(" />")
  377.         if elem.tail:
  378.             write(etree._escape_cdata(elem.tail))
  379.     #Redirecting
  380.     etree._serialize_xml = _serialize_xml
  381.  
  382. if(ver[0]=="2"):
  383. #For Python 2.4 there is no serializer. Changing to my method.
  384.     def _escape_attrib(text, encoding=None, replace=etree.string.replace):
  385.         # escape attribute value
  386.         try:
  387.             if encoding:
  388.                 try:
  389.                     text = etree._encode(text, encoding)
  390.                 except UnicodeError:
  391.                     return etree._encode_entity(text)
  392.             text = replace(text, "&", "&amp;")
  393.             text = replace(text, "\"", "&quot;")
  394.             text = replace(text, "<", "&lt;")
  395.             text = replace(text, ">", "&gt;")
  396.             return text
  397.         except (TypeError, AttributeError):
  398.             etree._raise_serialization_error(text)
  399.     etree._escape_attrib = _escape_attrib
  400.     def _write(self, file, node, encoding, namespaces):
  401.         # write XML to file
  402.         tag = node.tag
  403.         if tag is etree.Comment:
  404.             file.write("<!-- %s -->" % etree._escape_cdata(node.text, encoding))
  405.         elif tag is etree.ProcessingInstruction:
  406.             file.write("<?%s?>" % etree._escape_cdata(node.text, encoding))
  407.         else:
  408.             items = node.items()
  409.             xmlns_items = [] # new namespaces in this scope
  410.             try:
  411.                 if isinstance(tag, etree.QName) or tag[:1] == "{":
  412.                     tag, xmlns = fixtag(tag, namespaces)
  413.                     if xmlns: xmlns_items.append(xmlns)
  414.             except TypeError:
  415.                 etree._raise_serialization_error(tag)
  416.             file.write("<" + etree._encode(tag, encoding))
  417.             if items or xmlns_items:
  418.                 # NO !!!!lexical order
  419.                 for k, v in items:
  420.                     try:
  421.                         if isinstance(k, etree.QName) or k[:1] == "{":
  422.                             k, xmlns = fixtag(k, namespaces)
  423.                             if xmlns: xmlns_items.append(xmlns)
  424.                     except TypeError:
  425.                         etree._raise_serialization_error(k)
  426.                     try:
  427.                         if isinstance(v, etree.QName):
  428.                             v, xmlns = fixtag(v, namespaces)
  429.                             if xmlns: xmlns_items.append(xmlns)
  430.                     except TypeError:
  431.                         etree._raise_serialization_error(v)
  432.                     file.write(" %s=\"%s\"" % (etree._encode(k, encoding),
  433.                                                etree._escape_attrib(v, encoding)))
  434.                 for k, v in xmlns_items:
  435.                     file.write(" %s=\"%s\"" % (etree._encode(k, encoding),
  436.                                                etree._escape_attrib(v, encoding)))
  437.             if node.text or len(node):
  438.                 file.write(">")
  439.                 if node.text:
  440.                     file.write(etree._escape_cdata(node.text, encoding))
  441.                 for n in node:
  442.                     self._write(file, n, encoding, namespaces)
  443.                 file.write("</" + etree._encode(tag, encoding) + ">")
  444.             else:
  445.                 file.write(" />")
  446.             for k, v in xmlns_items:
  447.                 del namespaces[v]
  448.         if node.tail:
  449.             file.write(etree._escape_cdata(node.tail, encoding))
  450. #Redirecting...
  451.     etree.ElementTree._write=_write
  452. #Location founder function
  453. def loctree(current,root):
  454.     if current == root:
  455.         return("/"+root.tag)
  456.     else:
  457.         c_node=current
  458.         location=""
  459.         if current.get('name'):
  460.             location=current.tag+" "+current.get('name')
  461.         elif len(list(current.keys()))!=0 and current.get(list(current.keys())[0]):
  462.             location=current.tag+" "+list(current.keys())[0]+"="+current.get(list(current.keys())[0])
  463.         else:
  464.             location=current.tag
  465.         build=0
  466.         c_element=root
  467.         while(c_node!=root):
  468.             nlist=list(root)
  469.             nlist.insert(0,root)
  470.             for node in nlist:
  471.                 if list(node):
  472.                     nlist+=list(node)
  473.                 for child in list(node):
  474.                     if child==c_node:
  475.                         c_node=node
  476.                         if node.get('name'):
  477.                             location=node.tag+" "+node.get('name')+"/"+location
  478.                         elif len(list(node.keys()))!=0 and node.get(list(node.keys())[0]):
  479.                             location=node.tag+" "+list(node.keys())[0]+"="+node.get(list(node.keys())[0])+"/"+location
  480.                         else:
  481.                             location=node.tag+"/"+location
  482.                         if node == root:
  483.                             location="/"+location
  484.                         break
  485.         return(location)  
  486. #MAIN SH FUNCTION
  487. def XMLsh():
  488.     tui=0
  489.     print("Python version: "+ver[0])
  490.     if(ver[0]=="3"):
  491.         fname=input('Enter filename to work with. Default is /var/xapi/state.db: ')
  492.     elif(ver[0]=="2"):
  493.         fname=raw_input('Enter filename to work with. Default is /var/xapi/state.db: ')
  494.     else:
  495.         fname=0
  496.         print("Something with Python version ?")
  497.         return 0
  498.     if fname=="":
  499.         fname="/var/xapi/state.db"
  500.     try:
  501.         tree=etree.parse(fname)
  502.         root=tree.getroot()
  503.     except:
  504.         print("Something goes wrong. Check file? Exiting..")
  505.         return 0
  506.     current=root
  507.     parent=None
  508.     while(tui!=-1):
  509.         if(ver[0]=="3"):
  510.             tui=input('#:')
  511.         elif(ver[0]=="2"):
  512.             tui=raw_input('#:')
  513.         if tui != '':
  514.             tui=list(tui.split())
  515. # Here goes commands
  516. # Command list / ls
  517.             if tui[0]=="list" or tui[0]=="ls":
  518.                 for node in list(current):
  519.                     if node.get('name'):
  520.                         print(node.tag+" "+node.get('name'))
  521.                     elif len(list(node.keys()))!=0 and node.get(list(node.keys())[0]):
  522.                         print(node.tag+" "+list(node.keys())[0]+"="+node.get(list(node.keys())[0]))
  523.                     else:
  524.                         print(node.tag)      
  525.                 for key in list(current.keys()):
  526.                     print(key+"="+current.get(key))
  527.                 if current.text != None:
  528.                     print("Tag text:")
  529.                     print(current.text)
  530.                    
  531. # Command la (list attributes)
  532.             elif tui[0] == "la":
  533.                 for key in list(current.keys()):
  534.                     print(key+"="+current.get(key))
  535.                 if current.text != None:
  536.                     print("Tag text:")
  537.                     print(current.text)
  538. # Command exit
  539.             elif tui[0] == "exit":
  540.                 tui=-1
  541. # Command who
  542.             elif tui[0] == "who":
  543.                 print(loctree(current,root))                  
  544. # Command cd
  545.             elif tui[0] == "cd" and len(tui) > 1:    
  546.                 if tui[1] != ".." and tui[1] != "/":
  547.                     tui.pop(0)
  548.                     tui=" ".join(tui).strip()
  549.                     tui=tui.split("/")
  550.                     iferror=current
  551.                     for move in tui:
  552.                         if move=='' and len(tui)>2 and tui[1]!=root.tag:
  553.                             current=root
  554.                         if move==root.tag:
  555.                             current=root
  556.                             parent=None
  557.                         for node in list(current):
  558.                             if node.get('name') and node.get('name')==move:
  559.                                 parent=current
  560.                                 current=node
  561.                             elif node.get('name') and move==node.tag+" "+node.get('name'):
  562.                                 parent=current
  563.                                 current=node
  564.                             elif len(list(node.keys()))!=0 and move==node.tag+" "+list(node.keys())[0]+"="+node.get(list(node.keys())[0]):
  565.                                 parent=current
  566.                                 current=node
  567.                             elif str(node.tag)==move:
  568.                                 parent=current
  569.                                 current=node
  570.                     if iferror==current:
  571.                         print("No such instance.")
  572.                 elif tui[1] == "/":
  573.                     current=root
  574.                     parent=None
  575.                 elif tui[1] == "..":
  576.                     if parent != None:
  577.                         current=parent
  578.                         c_element=root
  579.                         nlist=list(root)
  580.                         nlist.insert(0,root)
  581.                         for node in nlist:
  582.                             if list(node):
  583.                                 nlist+=list(node)
  584.                             for child in list(node):
  585.                                 if child==current:
  586.                                     parent=node
  587.                                     break
  588. # Command set
  589.             elif tui[0]=="set":
  590.                 tui.pop(0)
  591.                 target=tui.pop(0)
  592.                 tui=" ".join(tui).strip()
  593.                 if target in list(current.keys()):
  594.                     current.set(target,tui)
  595.                 else:
  596.                     print("No such attribute")
  597. # Command add
  598.             elif tui[0]=="add":
  599.                 tui.pop(0)
  600.                 target=tui.pop(0)
  601.                 tui=" ".join(tui).strip()
  602.                 if target in list(current.keys()):
  603.                     print("Can't add attribute. Already exist.")
  604.                 else:
  605.                     current.set(target,tui)
  606. # Command settext
  607.             elif tui[0]=="settext":
  608.                 tui.pop(0)
  609.                 tui=" ".join(tui).strip()
  610.                 current.text=tui
  611. # Command locate, find
  612.             elif tui[0]=="locate" or tui[0]=="find":
  613.                 result=""
  614.                 mode=tui.pop(0)
  615.                 tui=" ".join(tui).strip()
  616.                 c_element=root
  617.                 nlist=list(root)
  618.                 nlist.insert(len(nlist)-1,root)
  619.                 for node in nlist:
  620.                     if list(node):
  621.                         nlist+=list(node)
  622.                     for child in list(node):
  623.                         if tui==child.tag or (str(child.tag).find(tui)!=-1 and mode=="find"):
  624.                             print(loctree(child,root))
  625.                         for key in list(child.keys()):
  626.                             if str(key)==tui:
  627.                                 print(loctree(child,root)+"/"+tui+"="+str(child.get(tui)))
  628.                             if str(child.get(key))==tui:
  629.                                 print(loctree(child,root)+"/"+key+"="+child.get(key))
  630.                             if str(child.text)==tui:
  631.                                 print(loctree(child,root)+"/"+tui)
  632.                         if mode=="find":
  633.                             if str(child.text).find(tui)!=-1:
  634.                                 print(loctree(child,root)+"/"+child.text)
  635.                             for key in list(child.keys()):
  636.                                 if str(key).find(tui)!=-1:
  637.                                     print(loctree(child,root)+"/"+tui+"="+str(child.get(tui)))
  638.                                 if str(child.get(key)).find(tui)!=-1:
  639.                                     print(loctree(child,root)+"/"+key+"="+child.get(key))          
  640. # Command xapi
  641.             elif tui[0]=="xapi":
  642.                 tui.pop(0)
  643.                 tui=" ".join(tui).strip()
  644.                 if(tui=="start"):
  645.                     print(call("/etc/init.d/xapi start", shell=True))
  646.                 elif(tui=="stop"):
  647.                     print(call("/etc/init.d/xapi stop", shell=True))
  648.                 elif(tui=="restart"):
  649.                     print(call("/etc/init.d/xapi restart", shell=True))
  650.                 else:
  651.                     print("Usage: xapi <start,stop,restart>")                                  
  652. # Command save
  653.             elif tui[0]=="save":
  654.                 if(ver[0]=="3"):
  655.                     loc=input("Enter filename to save. Default is /var/xapi/state.db: ")
  656.                 elif(ver[0]=="2"):
  657.                     loc=raw_input("Enter filename to save. Default is /var/xapi/state.db: ")
  658.                 if loc=="":
  659.                         tree.write("/var/xapi/state.db")
  660.                 else:
  661.                         tree.write(loc)
  662. # Command ?/help
  663.             elif tui[0]=="?" or tui[0]=="help":
  664.                 print("XML shell parser commands:")
  665.                 print("ls/list : List childs in current tag")
  666.                 print("la : List attributes in current tag")
  667.                 print("who : Show current location")
  668.                 print("cd : Change directory to <child_name> or <..> to parent node. For enumerated row select: cd row <row_number>")
  669.                 print("set : Change attribute value. Usage: set <attribute> <value>")
  670.                 print("add : Add attribute. Usage: add <attribute> <value>")
  671.                 print("settext : Change tag text block. Usage: settext <text>")
  672.                 print("locate : Locate exact key/value. Usage: locate <value>")
  673.                 print("find : Find all ocurrences of value. Usage: find <value>")
  674.                 print("xapi : Manage XAPI. Usage: xapi <start/stop/restart>")
  675.                 print("save : Save file.")
  676.                 print("?/help : Show this message")
  677.                 print("! : Debug mode. Direct python command execution. Usage: ! <command>")  
  678. # Debug mode for direct python commands input
  679.             elif tui[0]=="!":
  680.                 try:
  681.                     print(eval(tui[1]))
  682.                 except:
  683.                     print ("Something goes wrong..")
  684. # Incorrect command
  685.             else:
  686.                 tui=" ".join(tui).strip()
  687.                 print("No such command "+tui)
  688. XMLsh()
  689.  
  690.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement