tools.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 colorama
  30. # import traceback
  31. if sys.platform != 'win32':
  32. import termios
  33. import fcntl
  34. import tty
  35. try:
  36. import pyreadline as readline
  37. _readline_available = True
  38. except ImportError:
  39. _readline_available = False
  40. # raise ImportError("You need 'pyreadline' on Windows")
  41. else:
  42. try:
  43. import readline
  44. _readline_available = True
  45. except ImportError, e:
  46. _readline_available = False
  47. _defaultwidth = 10
  48. class ANSI(object):
  49. """
  50. ANSI Colors
  51. """
  52. Reset = 0
  53. Bold = 1
  54. Underscore = 2
  55. Black = 30
  56. Red = 31
  57. Green = 32
  58. Yellow = 33
  59. Blue = 34
  60. Magenta = 35
  61. Cyan = 36
  62. White = 37
  63. def typeset(text, color, bold=False, underline=False):
  64. """
  65. print colored strings using colorama
  66. """
  67. if not config.get_value("Global", "colors") == 'yes':
  68. return text
  69. if bold:
  70. text = colorama.Style.BRIGHT + text
  71. if underline and not 'win32' in sys.platform:
  72. text = ANSI.Underscore + text
  73. return color+text+colorama.Style.RESET_ALL
  74. def select(question, possible):
  75. """
  76. select input from user
  77. """
  78. for i in range(0, len(possible)):
  79. print ("%d - %-"+str(_defaultwidth)+"s") % (i+1, possible[i])
  80. while 1:
  81. uinput = getonechar(question)
  82. if uinput.isdigit() and int(uinput) in range(1, len(possible)+1):
  83. return possible[int(uinput)-1]
  84. def text_to_clipboards(text):
  85. """
  86. copy text to clipboard
  87. credit:
  88. https://pythonadventures.wordpress.com/tag/xclip/
  89. """
  90. # "primary":
  91. try:
  92. xsel_proc = sp.Popen(['xsel', '-pi'], stdin=sp.PIPE)
  93. xsel_proc.communicate(text)
  94. # "clipboard":
  95. xsel_proc = sp.Popen(['xsel', '-bi'], stdin=sp.PIPE)
  96. xsel_proc.communicate(text)
  97. except OSError, e:
  98. print e, "\nExecuting xsel failed, is it installed ?\n \
  99. please check your configuration file ... "
  100. def text_to_mcclipboard(text):
  101. """
  102. copy text to mac os x clip board
  103. credit:
  104. https://pythonadventures.wordpress.com/tag/xclip/
  105. """
  106. # "primary":
  107. try:
  108. pbcopy_proc = sp.Popen(['pbcopy'], stdin=sp.PIPE)
  109. pbcopy_proc.communicate(text)
  110. except OSError, e:
  111. print e, "\nExecuting pbcoy failed..."
  112. def open_url(link, macosx=False):
  113. """
  114. launch xdg-open or open in MacOSX with url
  115. """
  116. uopen = "xdg-open"
  117. if macosx:
  118. uopen = "open"
  119. try:
  120. sp.Popen([uopen, link], stdin=sp.PIPE)
  121. except OSError, e:
  122. print "Executing open_url failed with:\n", e
  123. def getpassword(question, width=_defaultwidth, echo=False):
  124. if echo:
  125. print question.ljust(width),
  126. return sys.stdin.readline().rstrip()
  127. else:
  128. while 1:
  129. a1 = getpass.getpass(question.ljust(width))
  130. if len(a1) == 0:
  131. return a1
  132. a2 = getpass.getpass("[Repeat] %s" % (question.ljust(width)))
  133. if a1 == a2:
  134. return a1
  135. else:
  136. print "Passwords don't match. Try again."
  137. def gettermsize():
  138. s = struct.pack("HHHH", 0, 0, 0, 0)
  139. f = sys.stdout.fileno()
  140. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  141. rows, cols, width, height = struct.unpack("HHHH", x)
  142. return rows, cols
  143. def getinput(question, default="", completer=None, width=_defaultwidth):
  144. if not _readline_available:
  145. return raw_input(question.ljust(width))
  146. else:
  147. def defaulter():
  148. """define default behavior startup"""
  149. if _readline_available:
  150. readline.insert_text(default)
  151. readline.set_startup_hook(defaulter)
  152. oldcompleter = readline.get_completer()
  153. readline.set_completer(completer)
  154. x = raw_input(question.ljust(width))
  155. readline.set_completer(completer)
  156. readline.set_startup_hook()
  157. return x
  158. def getyesno(question, defaultyes=False, width=_defaultwidth):
  159. if (defaultyes):
  160. default = "[Y/n]"
  161. else:
  162. default = "[y/N]"
  163. ch = getonechar("%s %s" % (question, default), width)
  164. if (ch == '\n'):
  165. if (defaultyes):
  166. return True
  167. else:
  168. return False
  169. elif (ch == 'y' or ch == 'Y'):
  170. return True
  171. elif (ch == 'n' or ch == 'N'):
  172. return False
  173. else:
  174. return getyesno(question, defaultyes, width)
  175. class CliMenu(object):
  176. def __init__(self):
  177. self.items = []
  178. def add(self, item):
  179. if (isinstance(item, CliMenuItem)):
  180. self.items.append(item)
  181. else:
  182. print item.__class__
  183. def run(self):
  184. while True:
  185. i = 0
  186. for x in self.items:
  187. i = i + 1
  188. current = x.getter()
  189. currentstr = ''
  190. if type(current) == list:
  191. for c in current:
  192. currentstr += ("%s " % (c))
  193. else:
  194. currentstr = current
  195. print ("%d - %-"+str(_defaultwidth)
  196. + "s %s") % (i, x.name+":",
  197. currentstr)
  198. print "%c - Finish editing" % ('X')
  199. option = getonechar("Enter your choice:")
  200. try:
  201. print "selection, ", option
  202. # substract 1 because array subscripts start at 0
  203. selection = int(option) - 1
  204. # new value is created by calling the editor with the
  205. # previous value as a parameter
  206. # TODO: enable overriding password policy as if new node
  207. # is created.
  208. if selection == 1: # for password
  209. value = self.items[selection].editor(0)
  210. else:
  211. edit = self.items[selection].getter()
  212. value = self.items[selection].editor(edit)
  213. self.items[selection].setter(value)
  214. except (ValueError, IndexError):
  215. if (option.upper() == 'X'):
  216. break
  217. print "Invalid selection"
  218. def getonechar(question, width=_defaultwidth):
  219. question = "%s " % (question)
  220. print question.ljust(width),
  221. sys.stdout.flush()
  222. fd = sys.stdin.fileno()
  223. tty_mode = tty.tcgetattr(fd)
  224. tty.setcbreak(fd)
  225. try:
  226. ch = os.read(fd, 1)
  227. finally:
  228. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  229. print ch
  230. return ch
  231. class CliMenuItem(object):
  232. def __init__(self, name, editor, getter, setter):
  233. self.name = name
  234. self.editor = editor
  235. self.getter = getter
  236. self.setter = setter
  237. class CLICallback(Callback):
  238. def getinput(self, question):
  239. return raw_input(question)
  240. def getsecret(self, question):
  241. return getpass.getpass(question + ":")