cli.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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) 2012 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  20. #============================================================================
  21. # pylint: disable=I0011
  22. """
  23. Define the CLI interface for pwman3 and the helper functions
  24. """
  25. from __future__ import print_function
  26. import pwman
  27. import pwman.exchange.importer as importer
  28. import pwman.exchange.exporter as exporter
  29. import pwman.util.generator as generator
  30. from pwman.data.nodes import Node
  31. from pwman.data.nodes import NewNode
  32. from pwman.data.tags import Tag
  33. from pwman.data.tags import TagNew as TagN
  34. from pwman.util.crypto import CryptoEngine
  35. from pwman.util.crypto import zerome
  36. import pwman.util.config as config
  37. import re
  38. import sys
  39. import os
  40. import cmd
  41. import time
  42. import select as uselect
  43. import ast
  44. from pwman.ui import tools
  45. from pwman.ui.tools import CliMenu, CMDLoop
  46. from pwman.ui.tools import CliMenuItem
  47. from pwman.ui.ocli import PwmanCliOld
  48. from colorama import Fore
  49. from pwman.ui.base import HelpUI, BaseUI
  50. import getpass
  51. from pwman.ui.tools import CLICallback
  52. try:
  53. import readline
  54. _readline_available = True
  55. except ImportError, e: # pragma: no cover
  56. _readline_available = False
  57. def get_pass_conf():
  58. numerics = config.get_value("Generator", "numerics").lower() == 'true'
  59. # TODO: allow custom leetifying through the config
  60. leetify = config.get_value("Generator", "leetify").lower() == 'true'
  61. special_chars = config.get_value("Generator", "special_chars"
  62. ).lower() == 'true'
  63. return numerics, leetify, special_chars
  64. class BaseCommands(PwmanCliOld):
  65. """
  66. Inherit from the old class, override
  67. all the methods related to tags, and
  68. newer Node format, so backward compatability is kept...
  69. Commands defined here, can have aliases definded in Aliases.
  70. You can define the aliases here too, but it makes
  71. the class code really long and unclear.
  72. """
  73. def do_copy(self, args):
  74. if self.hasxsel:
  75. ids = self.get_ids(args)
  76. if len(ids) > 1:
  77. print ("Can copy only 1 password at a time...")
  78. return None
  79. try:
  80. node = self._db.getnodes(ids)
  81. tools.text_to_clipboards(node[0].password)
  82. print ("copied password for {}@{} clipboard".format(
  83. node[0].username, node[0].url))
  84. print ("erasing in 10 sec...")
  85. time.sleep(10)
  86. tools.text_to_clipboards("")
  87. except Exception, e:
  88. self.error(e)
  89. else:
  90. print ("Can't copy to clipboard, no xsel found in the system!")
  91. def do_open(self, args):
  92. ids = self.get_ids(args)
  93. if not args:
  94. self.help_open()
  95. return
  96. if len(ids) > 1:
  97. print ("Can open only 1 link at a time ...")
  98. return None
  99. try:
  100. node = self._db.getnodes(ids)
  101. url = node[0].url
  102. tools.open_url(url)
  103. except Exception, e:
  104. self.error(e)
  105. def do_edit(self, arg):
  106. ids = self.get_ids(arg)
  107. for i in ids:
  108. try:
  109. i = int(i)
  110. node = self._db.getnodes([i])[0]
  111. menu = CMDLoop()
  112. print ("Editing node %d." % (i))
  113. menu.add(CliMenuItem("Username", self.get_username,
  114. node.username,
  115. node.username))
  116. menu.add(CliMenuItem("Password", self.get_password,
  117. node.password,
  118. node.password))
  119. menu.add(CliMenuItem("Url", self.get_url,
  120. node.url,
  121. node.url))
  122. menunotes = CliMenuItem("Notes", self.get_notes,
  123. node.notes,
  124. node.notes)
  125. menu.add(menunotes)
  126. menu.add(CliMenuItem("Tags", self.get_tags,
  127. node.tags,
  128. node.tags))
  129. menu.run(node)
  130. self._db.editnode(i, node)
  131. # when done with node erase it
  132. zerome(node._password)
  133. except Exception, e:
  134. self.error(e)
  135. def print_node(self, node):
  136. width = str(tools._defaultwidth)
  137. print ("Node %d." % (node._id))
  138. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  139. node.username))
  140. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  141. node.password))
  142. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  143. node.url))
  144. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  145. node.notes))
  146. print (tools.typeset("Tags: ", Fore.RED)),
  147. for t in node.tags:
  148. print (" %s " % t)
  149. print()
  150. def heardEnter():
  151. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  152. for s in i:
  153. if s == sys.stdin:
  154. sys.stdin.readline()
  155. return True
  156. return False
  157. def waituntil_enter(somepredicate, timeout, period=0.25):
  158. mustend = time.time() + timeout
  159. while time.time() < mustend:
  160. cond = somepredicate()
  161. if cond:
  162. break
  163. time.sleep(period)
  164. self.do_cls('')
  165. try:
  166. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  167. except ValueError:
  168. flushtimeout = 10
  169. if flushtimeout > 0:
  170. print ("Type Enter to flush screen (autoflash in "
  171. "%d sec.)" % flushtimeout)
  172. waituntil_enter(heardEnter, flushtimeout)
  173. def do_tags(self, arg):
  174. enc = CryptoEngine.get()
  175. if not enc.alive():
  176. enc._getcipher()
  177. print ("Tags: \n",)
  178. t = self._tags(enc)
  179. print ('\n'.join(t))
  180. def get_tags(self, default=None, reader=raw_input):
  181. """read tags from user"""
  182. defaultstr = ''
  183. if default:
  184. for t in default:
  185. defaultstr += "%s " % (t)
  186. else:
  187. # tags = self._db.currenttags()
  188. tags = self._db._filtertags
  189. for t in tags:
  190. defaultstr += "%s " % (t)
  191. # strings = []
  192. tags = self._db.listtags(True)
  193. #for t in tags:
  194. # strings.append(t.get_name())
  195. # strings.append(t)
  196. strings = [t for t in tags]
  197. def complete(text, state):
  198. count = 0
  199. for s in strings:
  200. if s.startswith(text):
  201. if count == state:
  202. return s
  203. else:
  204. count += 1
  205. taglist = tools.getinput("Tags: ", defaultstr, completer=complete,
  206. reader=reader)
  207. tagstrings = taglist.split()
  208. tags = [TagN(tn) for tn in tagstrings]
  209. return tags
  210. def do_list(self, args):
  211. if len(args.split()) > 0:
  212. self.do_clear('')
  213. self.do_filter(args)
  214. try:
  215. if sys.platform != 'win32':
  216. rows, cols = tools.gettermsize()
  217. else:
  218. rows, cols = 18, 80 # fix this !
  219. nodeids = self._db.listnodes()
  220. nodes = self._db.getnodes(nodeids)
  221. cols -= 8
  222. i = 0
  223. for n in nodes:
  224. tags = n.tags
  225. tags = filter(None, tags)
  226. tagstring = ''
  227. first = True
  228. for t in tags:
  229. if not first:
  230. tagstring += ", "
  231. else:
  232. first = False
  233. tagstring += t
  234. name = "%s@%s" % (n.username, n.url)
  235. name_len = cols * 2 / 3
  236. tagstring_len = cols / 3
  237. if len(name) > name_len:
  238. name = name[:name_len - 3] + "..."
  239. if len(tagstring) > tagstring_len:
  240. tagstring = tagstring[:tagstring_len - 3] + "..."
  241. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  242. formatted_entry = tools.typeset(fmt % (n._id,
  243. name, tagstring),
  244. Fore.YELLOW, False)
  245. print (formatted_entry)
  246. i += 1
  247. if i > rows - 2:
  248. i = 0
  249. c = tools.getonechar("Press <Space> for more,"
  250. " or 'Q' to cancel")
  251. if c.lower() == 'q':
  252. break
  253. except Exception, e:
  254. self.error(e)
  255. def do_filter(self, args):
  256. tagstrings = args.split()
  257. try:
  258. tags = [TagN(ts) for ts in tagstrings]
  259. self._db.filter(tags)
  260. tags = self._db.currenttags()
  261. print ("Current tags: ",)
  262. if len(tags) == 0:
  263. print ("None",)
  264. for t in tags:
  265. print ("%s " % (t.name),)
  266. print
  267. except Exception, e:
  268. self.error(e)
  269. def do_new(self, args):
  270. """
  271. can override default config settings the following way:
  272. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  273. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  274. Password (Blank to generate):
  275. """
  276. errmsg = ("could not parse config override, please input some"
  277. " kind of dictionary, e.g.: n {'leetify':False, "
  278. " numerics':True, 'special_chars':True}")
  279. try:
  280. username = self.get_username()
  281. if args:
  282. try:
  283. args = ast.literal_eval(args)
  284. except Exception:
  285. raise Exception(errmsg)
  286. if not isinstance(args, dict):
  287. raise Exception(errmsg)
  288. password = self.get_password(argsgiven=1, **args)
  289. else:
  290. numerics, leet, s_chars = get_pass_conf()
  291. password = self.get_password(argsgiven=0,
  292. numerics=numerics,
  293. symbols=leet,
  294. special_signs=s_chars)
  295. url = self.get_url()
  296. notes = self.get_notes()
  297. node = NewNode(username, password, url, notes)
  298. node.tags = self.get_tags()
  299. self._db.addnodes([node])
  300. print ("Password ID: %d" % (node._id))
  301. # when done with node erase it
  302. zerome(password)
  303. except Exception, e:
  304. self.error(e)
  305. def do_print(self, arg):
  306. for i in self.get_ids(arg):
  307. try:
  308. node = self._db.getnodes([i])
  309. self.print_node(node[0])
  310. # when done with node erase it
  311. zerome(node[0]._password)
  312. except Exception, e:
  313. self.error(e)
  314. def do_delete(self, arg):
  315. ids = self.get_ids(arg)
  316. try:
  317. nodes = self._db.getnodes(ids)
  318. for n in nodes:
  319. try:
  320. b = tools.getyesno(("Are you sure you want to"
  321. " delete '%s@%s'?"
  322. ) % (n.username, n.url), False)
  323. except NameError:
  324. pass
  325. if b is True:
  326. self._db.removenodes([n])
  327. print ("%s@%s deleted" % (n.username, n.url))
  328. except Exception, e:
  329. self.error(e)
  330. def get_password(self, argsgiven, numerics=False, leetify=False,
  331. symbols=False, special_signs=False,
  332. reader=getpass.getpass, length=None):
  333. return tools.getpassword("Password (Blank to generate): ",
  334. reader=reader, length=length, leetify=leetify)
  335. class Aliases(BaseCommands, PwmanCliOld):
  336. """
  337. Define all the alias you want here...
  338. """
  339. def do_cp(self, args):
  340. self.do_copy(args)
  341. def do_e(self, arg):
  342. self.do_edit(arg)
  343. def do_EOF(self, args):
  344. return self.do_exit(args)
  345. def do_l(self, args):
  346. self.do_list(args)
  347. def do_ls(self, args):
  348. self.do_list(args)
  349. def do_p(self, arg):
  350. self.do_print(arg)
  351. def do_rm(self, arg):
  352. self.do_delete(arg)
  353. def do_o(self, args):
  354. self.do_open(args)
  355. def do_h(self, arg):
  356. self.do_help(arg)
  357. def do_n(self, arg):
  358. self.do_new(arg)
  359. class PwmanCliNew(Aliases, BaseCommands):
  360. """
  361. Inherit from the BaseCommands and Aliases
  362. """
  363. def __init__(self, db, hasxsel, callback):
  364. """
  365. initialize CLI interface, set up the DB
  366. connecion, see if we have xsel ...
  367. """
  368. cmd.Cmd.__init__(self)
  369. self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version,
  370. pwman.website)
  371. self._historyfile = config.get_value("Readline", "history")
  372. self.hasxsel = hasxsel
  373. try:
  374. enc = CryptoEngine.get()
  375. enc._callback = callback()
  376. self._db = db
  377. self._db.open()
  378. except Exception, e: # pragma: no cover
  379. self.error(e)
  380. sys.exit(1)
  381. try:
  382. readline.read_history_file(self._historyfile)
  383. except IOError, e: # pragma: no cover
  384. pass
  385. self.prompt = "pwman> "