tools.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2013 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. """
  20. Define the CLI interface for pwman3 and the helper functions
  21. """
  22. from pwman.util.callback import Callback
  23. import pwman.util.config as config
  24. import subprocess as sp
  25. import getpass
  26. import sys
  27. import struct
  28. import os
  29. # import traceback
  30. if sys.platform != 'win32':
  31. import termios
  32. import fcntl
  33. import tty
  34. _defaultwidth = 10
  35. try:
  36. import readline
  37. _readline_available = True
  38. except ImportError, e:
  39. _readline_available = False
  40. class ANSI(object):
  41. """
  42. ANSI Colors
  43. """
  44. Reset = 0
  45. Bold = 1
  46. Underscore = 2
  47. Black = 30
  48. Red = 31
  49. Green = 32
  50. Yellow = 33
  51. Blue = 34
  52. Magenta = 35
  53. Cyan = 36
  54. White = 37
  55. def typeset(text, color, bold=False, underline=False):
  56. """print colored strings"""
  57. if not config.get_value("Global", "colors") == 'yes':
  58. return text
  59. if (bold):
  60. bold = "%d ;" % (ANSI.Bold)
  61. else:
  62. bold = ""
  63. if (underline):
  64. underline = "%d;" % (ANSI.Underscore)
  65. else:
  66. underline = ""
  67. return "\033[%s%s%sm%s\033[%sm" % (bold, underline, color,
  68. text, ANSI.Reset)
  69. def select(question, possible):
  70. """
  71. select input from user
  72. """
  73. for i in range(0, len(possible)):
  74. print ("%d - %-"+str(_defaultwidth)+"s") % (i+1, possible[i])
  75. while 1:
  76. uinput = getonechar(question)
  77. if uinput.isdigit() and int(uinput) in range(1, len(possible)+1):
  78. return possible[int(uinput)-1]
  79. def text_to_clipboards(text):
  80. """
  81. copy text to clipboard
  82. credit:
  83. https://pythonadventures.wordpress.com/tag/xclip/
  84. """
  85. # "primary":
  86. try:
  87. xsel_proc = sp.Popen(['xsel', '-pi'], stdin=sp.PIPE)
  88. xsel_proc.communicate(text)
  89. # "clipboard":
  90. xsel_proc = sp.Popen(['xsel', '-bi'], stdin=sp.PIPE)
  91. xsel_proc.communicate(text)
  92. except OSError, e:
  93. print e, "\nExecuting xsel failed, is it installed ?\n \
  94. please check your configuration file ... "
  95. def text_to_mcclipboard(text):
  96. """
  97. copy text to mac os x clip board
  98. credit:
  99. https://pythonadventures.wordpress.com/tag/xclip/
  100. """
  101. # "primary":
  102. try:
  103. pbcopy_proc = sp.Popen(['pbcopy'], stdin=sp.PIPE)
  104. pbcopy_proc.communicate(text)
  105. except OSError, e:
  106. print e, "\nExecuting pbcoy failed..."
  107. def open_url(link, macosx=False):
  108. """
  109. launch xdg-open or open in MacOSX with url
  110. """
  111. uopen = "xdg-open"
  112. if macosx:
  113. uopen = "open"
  114. try:
  115. sp.Popen([uopen, link], stdin=sp.PIPE)
  116. except OSError, e:
  117. print "Executing open_url failed with:\n", e
  118. def getpassword(question, width=_defaultwidth, echo=False):
  119. if echo:
  120. print question.ljust(width),
  121. return sys.stdin.readline().rstrip()
  122. else:
  123. while 1:
  124. a1 = getpass.getpass(question.ljust(width))
  125. if len(a1) == 0:
  126. return a1
  127. a2 = getpass.getpass("[Repeat] %s" % (question.ljust(width)))
  128. if a1 == a2:
  129. return a1
  130. else:
  131. print "Passwords don't match. Try again."
  132. def gettermsize():
  133. s = struct.pack("HHHH", 0, 0, 0, 0)
  134. f = sys.stdout.fileno()
  135. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  136. rows, cols, width, height = struct.unpack("HHHH", x)
  137. return rows, cols
  138. def getinput(question, default="", completer=None, width=_defaultwidth):
  139. if (not _readline_available):
  140. return raw_input(question.ljust(width))
  141. else:
  142. def defaulter():
  143. """define default behavior startup"""
  144. readline.insert_text(default)
  145. readline.set_startup_hook(defaulter)
  146. oldcompleter = readline.get_completer()
  147. readline.set_completer(completer)
  148. x = raw_input(question.ljust(width))
  149. readline.set_completer(oldcompleter)
  150. readline.set_startup_hook()
  151. return x
  152. def getyesno(question, defaultyes=False, width=_defaultwidth):
  153. if (defaultyes):
  154. default = "[Y/n]"
  155. else:
  156. default = "[y/N]"
  157. ch = getonechar("%s %s" % (question, default), width)
  158. if (ch == '\n'):
  159. if (defaultyes):
  160. return True
  161. else:
  162. return False
  163. elif (ch == 'y' or ch == 'Y'):
  164. return True
  165. elif (ch == 'n' or ch == 'N'):
  166. return False
  167. else:
  168. return getyesno(question, defaultyes, width)
  169. class CliMenu(object):
  170. def __init__(self):
  171. self.items = []
  172. def add(self, item):
  173. if (isinstance(item, CliMenuItem)):
  174. self.items.append(item)
  175. else:
  176. print item.__class__
  177. def run(self):
  178. while True:
  179. i = 0
  180. for x in self.items:
  181. i = i + 1
  182. current = x.getter()
  183. currentstr = ''
  184. if type(current) == list:
  185. for c in current:
  186. currentstr += ("%s " % (c))
  187. else:
  188. currentstr = current
  189. print ("%d - %-"+str(_defaultwidth)+\
  190. "s %s") % (i, x.name+":",
  191. currentstr)
  192. print "%c - Finish editing" % ('X')
  193. option = getonechar("Enter your choice:")
  194. try:
  195. print "selection, ", option
  196. # substract 1 because array subscripts start at 0
  197. selection = int(option) - 1
  198. # new value is created by calling the editor with the
  199. # previous value as a parameter
  200. # TODO: enable overriding password policy as if new node
  201. # is created.
  202. if selection == 1: # for password
  203. value = self.items[selection].editor(0)
  204. else:
  205. edit = self.items[selection].getter()
  206. value = self.items[selection].editor(edit)
  207. self.items[selection].setter(value)
  208. except (ValueError, IndexError):
  209. if (option.upper() == 'X'):
  210. break
  211. print "Invalid selection"
  212. def getonechar(question, width=_defaultwidth):
  213. question = "%s " % (question)
  214. print question.ljust(width),
  215. sys.stdout.flush()
  216. fd = sys.stdin.fileno()
  217. tty_mode = tty.tcgetattr(fd)
  218. tty.setcbreak(fd)
  219. try:
  220. ch = os.read(fd, 1)
  221. finally:
  222. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  223. print ch
  224. return ch
  225. class CliMenuItem(object):
  226. def __init__(self, name, editor, getter, setter):
  227. self.name = name
  228. self.editor = editor
  229. self.getter = getter
  230. self.setter = setter
  231. class CLICallback(Callback):
  232. def getinput(self, question):
  233. return raw_input(question)
  234. def getsecret(self, question):
  235. return getpass.getpass(question + ":")