cli.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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
  46. from pwman.ui.tools import CliMenuItem
  47. from pwman.ui.tools import CLICallback
  48. from colorama import Fore
  49. from pwman.ui.base import HelpUI, BaseUI
  50. try:
  51. import readline
  52. _readline_available = True
  53. except ImportError, e:
  54. _readline_available = False
  55. # pylint: disable=R0904
  56. class PwmanCliOld(cmd.Cmd, HelpUI, BaseUI):
  57. """
  58. UI class for MacOSX
  59. """
  60. def error(self, exception):
  61. if (isinstance(exception, KeyboardInterrupt)):
  62. print('')
  63. else:
  64. print("Error: {0} ".format(exception))
  65. def do_exit(self, args):
  66. """exit the ui"""
  67. self._db.close()
  68. return True
  69. def get_ids(self, args):
  70. ids = []
  71. rex = re.compile(r"^(\d+)-(\d+)$")
  72. idstrs = args.split()
  73. for i in idstrs:
  74. m = rex.match(i)
  75. if m is None:
  76. try:
  77. ids.append(int(i))
  78. except ValueError:
  79. self._db.clearfilter()
  80. self._db.filter([Tag(i)])
  81. ids += self._db.listnodes()
  82. else:
  83. ids += range(int(m.group(1)),
  84. int(m.group(2)) + 1)
  85. return ids
  86. def get_filesystem_path(self, default="", reader=raw_input):
  87. return tools.getinput("Enter filename: ", default, reader=reader)
  88. def get_username(self, default="", reader=raw_input):
  89. return tools.getinput("Username: ", default, reader)
  90. def get_password(self, argsgiven, numerics=False, leetify=False,
  91. symbols=False, special_signs=False, reader=raw_input):
  92. """
  93. in the config file:
  94. numerics -> numerics
  95. leetify -> symbols
  96. special_chars -> special_signs
  97. """
  98. if argsgiven == 1:
  99. length = tools.getinput("Password length (default 7): ", "7")
  100. length = len(length)
  101. password, dumpme = generator.generate_password(length, length,
  102. True, leetify,
  103. numerics,
  104. special_signs)
  105. print ("New password: %s" % (password))
  106. return password
  107. # no args given
  108. password = tools.getpassword("Password (Blank to generate): ",
  109. tools._defaultwidth, False, reader)
  110. if not password:
  111. length = tools.getinput("Password length (default 7): ", "7")
  112. if length:
  113. length = int(length)
  114. else:
  115. length = 7
  116. password, dumpme = generator.generate_password(length, length,
  117. True, leetify,
  118. numerics,
  119. special_signs)
  120. print ("New password: %s" % (password))
  121. return password
  122. def get_url(self, default="", reader=raw_input):
  123. return tools.getinput("Url: ", default, reader)
  124. def get_notes(self, default="", reader=raw_input):
  125. return tools.getinput("Notes: ", default, reader)
  126. def get_tags(self, default=None):
  127. """read node tags from user"""
  128. defaultstr = ''
  129. if default:
  130. for t in default:
  131. defaultstr += "%s " % (t.get_name())
  132. else:
  133. tags = self._db.currenttags()
  134. for t in tags:
  135. defaultstr += "%s " % (t.get_name())
  136. strings = []
  137. tags = self._db.listtags(True)
  138. for t in tags:
  139. strings.append(t.get_name())
  140. def complete(text, state):
  141. count = 0
  142. for s in strings:
  143. if s.startswith(text):
  144. if count == state:
  145. return s
  146. else:
  147. count += 1
  148. taglist = tools.getinput("Tags: ", defaultstr, complete)
  149. tagstrings = taglist.split()
  150. tags = []
  151. for tn in tagstrings:
  152. tags.append(Tag(tn))
  153. return tags
  154. def print_node(self, node):
  155. width = str(tools._defaultwidth)
  156. print ("Node %d." % (node._id))
  157. print ("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  158. node.get_username())
  159. print ("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  160. node.get_password())
  161. print ("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  162. node.get_url())
  163. print ("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  164. node.get_notes())
  165. print (tools.typeset("Tags: ", Fore.RED)),
  166. for t in node.get_tags():
  167. print (" %s \n" % t.get_name()),
  168. def heardEnter():
  169. inpt, out, err = uselect.select([sys.stdin], [], [], 0.0001)
  170. for stream in inpt:
  171. if stream == sys.stdin:
  172. sys.stdin.readline()
  173. return True
  174. return False
  175. def waituntil_enter(somepredicate, timeout, period=0.25):
  176. mustend = time.time() + timeout
  177. while time.time() < mustend:
  178. cond = somepredicate()
  179. if cond:
  180. break
  181. time.sleep(period)
  182. self.do_cls('')
  183. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  184. if flushtimeout > 0:
  185. print ("Type Enter to flush screen (autoflash in "
  186. "%d sec.)" % flushtimeout)
  187. waituntil_enter(heardEnter, flushtimeout)
  188. def do_tags(self, arg):
  189. tags = self._db.listtags()
  190. if len(tags) > 0:
  191. tags[0].get_name() # hack to get password request before output
  192. print ("Tags: "),
  193. if len(tags) == 0:
  194. print ("None"),
  195. for t in tags:
  196. print ("%s " % (t.get_name())),
  197. print
  198. def complete_filter(self, text, line, begidx, endidx):
  199. strings = []
  200. enc = CryptoEngine.get()
  201. if not enc.alive():
  202. return strings
  203. tags = self._db.listtags()
  204. for t in tags:
  205. name = t.get_name()
  206. if name.startswith(text):
  207. strings.append(t.get_name())
  208. return strings
  209. def do_filter(self, args):
  210. tagstrings = args.split()
  211. try:
  212. tags = []
  213. for ts in tagstrings:
  214. tags.append(Tag(ts))
  215. self._db.filter(tags)
  216. tags = self._db.currenttags()
  217. print ("Current tags: "),
  218. if len(tags) == 0:
  219. print ("None"),
  220. for t in tags:
  221. print ("%s " % (t.get_name())),
  222. print
  223. except Exception, e:
  224. self.error(e)
  225. def do_clear(self, args):
  226. try:
  227. self._db.clearfilter()
  228. except Exception, e:
  229. self.error(e)
  230. def do_edit(self, arg):
  231. ids = self.get_ids(arg)
  232. for i in ids:
  233. try:
  234. i = int(i)
  235. node = self._db.getnodes([i])[0]
  236. menu = CliMenu()
  237. print ("Editing node %d." % (i))
  238. menu.add(CliMenuItem("Username", self.get_username,
  239. node.get_username,
  240. node.set_username))
  241. menu.add(CliMenuItem("Password", self.get_password,
  242. node.get_password,
  243. node.set_password))
  244. menu.add(CliMenuItem("Url", self.get_url,
  245. node.get_url,
  246. node.set_url))
  247. menu.add(CliMenuItem("Notes", self.get_notes,
  248. node.get_notes,
  249. node.set_notes))
  250. menu.add(CliMenuItem("Tags", self.get_tags,
  251. node.get_tags,
  252. node.set_tags))
  253. menu.run()
  254. self._db.editnode(i, node)
  255. # when done with node erase it
  256. zerome(node._password)
  257. except Exception, e:
  258. self.error(e)
  259. def do_import(self, arg):
  260. try:
  261. args = arg.split()
  262. if len(args) == 0:
  263. types = importer.Importer.types()
  264. intype = tools.select("Select filetype:", types)
  265. imp = importer.Importer.get(intype)
  266. infile = tools.getinput("Select file:")
  267. imp.import_data(self._db, infile)
  268. else:
  269. for i in args:
  270. types = importer.Importer.types()
  271. intype = tools.select("Select filetype:", types)
  272. imp = importer.Importer.get(intype)
  273. imp.import_data(self._db, i)
  274. except Exception, e:
  275. self.error(e)
  276. def do_export(self, arg):
  277. try:
  278. nodes = self.get_ids(arg)
  279. types = exporter.Exporter.types()
  280. ftype = tools.select("Select filetype:", types)
  281. exp = exporter.Exporter.get(ftype)
  282. out_file = tools.getinput("Select output file:")
  283. if len(nodes) > 0:
  284. b = tools.getyesno("Export nodes %s?" % (nodes), True)
  285. if not b:
  286. return
  287. exp.export_data(self._db, out_file, nodes)
  288. else:
  289. nodes = self._db.listnodes()
  290. tags = self._db.currenttags()
  291. tagstr = ""
  292. if len(tags) > 0:
  293. tagstr = " for "
  294. for t in tags:
  295. tagstr += "'%s' " % (t.get_name())
  296. b = tools.getyesno("Export all nodes%s?" % (tagstr), True)
  297. if not b:
  298. return
  299. exp.export_data(self._db, out_file, nodes)
  300. print ("Data exported.")
  301. except Exception, e:
  302. self.error(e)
  303. def do_new(self, args):
  304. """
  305. can override default config settings the following way:
  306. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  307. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  308. Password (Blank to generate):
  309. """
  310. errmsg = ("could not parse config override, please input some"
  311. " kind of dictionary, e.g.: n {'leetify':False, "
  312. " numerics':True, 'special_chars':True}")
  313. try:
  314. username = self.get_username()
  315. if args:
  316. try:
  317. args = ast.literal_eval(args)
  318. except Exception:
  319. raise Exception(errmsg)
  320. if not isinstance(args, dict):
  321. raise Exception(errmsg)
  322. password = self.get_password(1, **args)
  323. else:
  324. numerics = config.get_value("Generator",
  325. "numerics").lower() == 'true'
  326. # TODO: allow custom leetifying through the config
  327. leetify = config.get_value("Generator",
  328. "leetify").lower() == 'true'
  329. special_chars = config.get_value("Generator",
  330. "special_chars").lower() == \
  331. 'true'
  332. password = self.get_password(0,
  333. numerics=numerics,
  334. symbols=leetify,
  335. special_signs=special_chars)
  336. url = self.get_url()
  337. notes = self.get_notes()
  338. node = Node(username, password, url, notes)
  339. tags = self.get_tags()
  340. node.set_tags(tags)
  341. self._db.addnodes([node])
  342. print ("Password ID: %d" % (node.get_id()))
  343. except Exception, e:
  344. self.error(e)
  345. def do_print(self, arg):
  346. for i in self.get_ids(arg):
  347. try:
  348. node = self._db.getnodes([i])
  349. self.print_node(node[0])
  350. except Exception, e:
  351. self.error(e)
  352. def do_delete(self, arg):
  353. ids = self.get_ids(arg)
  354. try:
  355. nodes = self._db.getnodes(ids)
  356. for n in nodes:
  357. b = tools.getyesno("Are you sure you want to delete '%s@%s'?"
  358. % (n.get_username(), n.get_url()), False)
  359. if b is True:
  360. self._db.removenodes([n])
  361. print ("%s@%s deleted" % (n.get_username(), n.get_url()))
  362. except Exception, e:
  363. self.error(e)
  364. def do_list(self, args):
  365. """
  366. TODO: in order to make this code testable
  367. The functionality in this method should
  368. go to a method that returns a string.
  369. This method should only do the printing.
  370. """
  371. if len(args.split()) > 0:
  372. self.do_clear('')
  373. self.do_filter(args)
  374. try:
  375. if sys.platform != 'win32':
  376. rows, cols = tools.gettermsize()
  377. else:
  378. rows, cols = 18, 80
  379. nodeids = self._db.listnodes()
  380. nodes = self._db.getnodes(nodeids)
  381. cols -= 8
  382. i = 0
  383. for n in nodes:
  384. tags = n.get_tags()
  385. tagstring = ''
  386. first = True
  387. for t in tags:
  388. if not first:
  389. tagstring += ", "
  390. else:
  391. first = False
  392. tagstring += t.get_name()
  393. name = "%s@%s" % (n.get_username(), n.get_url())
  394. name_len = cols * 2 / 3
  395. tagstring_len = cols / 3
  396. if len(name) > name_len:
  397. name = name[:name_len - 3] + "..."
  398. if len(tagstring) > tagstring_len:
  399. tagstring = tagstring[:tagstring_len - 3] + "..."
  400. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  401. print (tools.typeset(fmt % (n.get_id(), name, tagstring),
  402. Fore.YELLOW, False))
  403. i += 1
  404. if i > rows - 2:
  405. i = 0
  406. c = tools.getonechar("Press <Space> for more, "
  407. "or 'Q' to cancel")
  408. if c == 'q':
  409. break
  410. except Exception, e:
  411. self.error(e)
  412. def do_forget(self, args):
  413. try:
  414. enc = CryptoEngine.get()
  415. enc.forget()
  416. except Exception, e:
  417. self.error(e)
  418. def do_passwd(self, args):
  419. try:
  420. self._db.changepassword()
  421. except Exception, e:
  422. self.error(e)
  423. def do_set(self, args):
  424. argstrs = args.split()
  425. try:
  426. if len(argstrs) == 0:
  427. conf = config.get_conf()
  428. for s in conf.keys():
  429. for n in conf[s].keys():
  430. print ("%s.%s = %s" % (s, n, conf[s][n]))
  431. elif len(argstrs) == 1:
  432. r = re.compile("(.+)\.(.+)")
  433. m = r.match(argstrs[0])
  434. if m is None or len(m.groups()) != 2:
  435. print ("Invalid option format")
  436. self.help_set()
  437. return
  438. print ("%s.%s = %s" % (m.group(1), m.group(2),
  439. config.get_value(m.group(1),
  440. m.group(2))))
  441. elif len(argstrs) == 2:
  442. r = re.compile("(.+)\.(.+)")
  443. m = r.match(argstrs[0])
  444. if m is None or len(m.groups()) != 2:
  445. print ("Invalid option format")
  446. self.help_set()
  447. return
  448. config.set_value(m.group(1), m.group(2), argstrs[1])
  449. else:
  450. self.help_set()
  451. except Exception, e:
  452. self.error(e)
  453. def do_save(self, args):
  454. argstrs = args.split()
  455. try:
  456. if len(argstrs) > 0:
  457. config.save(argstrs[0])
  458. else:
  459. config.save()
  460. print ("Config saved.")
  461. except Exception, e:
  462. self.error(e)
  463. def do_cls(self, args):
  464. os.system('clear')
  465. def do_copy(self, args):
  466. if self.hasxsel:
  467. ids = self.get_ids(args)
  468. if len(ids) > 1:
  469. print ("Can copy only 1 password at a time...")
  470. return None
  471. try:
  472. node = self._db.getnodes(ids)
  473. tools.text_to_clipboards(node[0].get_password())
  474. print ("copied password for {}@{} clipboard".format(
  475. node[0].get_username(), node[0].get_url()))
  476. print ("erasing in 10 sec...")
  477. time.sleep(10)
  478. tools.text_to_clipboards("")
  479. except Exception, e:
  480. self.error(e)
  481. else:
  482. print ("Can't copy to clipboard, no xsel found in the system!")
  483. def do_open(self, args):
  484. ids = self.get_ids(args)
  485. if not args:
  486. self.help_open()
  487. return
  488. if len(ids) > 1:
  489. print ("Can open only 1 link at a time ...")
  490. return None
  491. try:
  492. node = self._db.getnodes(ids)
  493. url = node[0].get_url()
  494. tools.open_url(url)
  495. except Exception, e:
  496. self.error(e)
  497. def postloop(self):
  498. try:
  499. readline.write_history_file(self._historyfile)
  500. except Exception:
  501. pass
  502. def __init__(self, db, hasxsel):
  503. """
  504. initialize CLI interface, set up the DB
  505. connecion, see if we have xsel ...
  506. """
  507. _dbwarning = "\n*** WARNNING: You are using the old database format" \
  508. + " which is unsecure." \
  509. + " It's highly recommended to switch to the new database " \
  510. + "format. Do note: support for this DB format will be dropped in"\
  511. + " v0.5." \
  512. + " Check the help (pwman3 -h) or look at the manpage which" \
  513. + " explains how to proceed. ***"
  514. cmd.Cmd.__init__(self)
  515. self.intro = "%s %s (c) visit: %s %s" % (pwman.appname, pwman.version,
  516. pwman.website, _dbwarning)
  517. self._historyfile = config.get_value("Readline", "history")
  518. self.hasxsel = hasxsel
  519. try:
  520. enc = CryptoEngine.get()
  521. enc.set_callback(CLICallback())
  522. self._db = db
  523. self._db.open()
  524. except Exception, e:
  525. self.error(e)
  526. sys.exit(1)
  527. try:
  528. readline.read_history_file(self._historyfile)
  529. except IOError, e:
  530. pass
  531. self.prompt = "!pwman> "
  532. class BaseCommands(PwmanCliOld):
  533. """
  534. Inherit from the old class, override
  535. all the methods related to tags, and
  536. newer Node format, so backward compatability is kept...
  537. Commands defined here, can have aliases definded in Aliases.
  538. You can define the aliases here too, but it makes
  539. the class code really long and unclear.
  540. """
  541. def do_copy(self, args):
  542. if self.hasxsel:
  543. ids = self.get_ids(args)
  544. if len(ids) > 1:
  545. print ("Can copy only 1 password at a time...")
  546. return None
  547. try:
  548. node = self._db.getnodes(ids)
  549. tools.text_to_clipboards(node[0].password)
  550. print ("copied password for {}@{} clipboard".format(
  551. node[0].username, node[0].url))
  552. print ("erasing in 10 sec...")
  553. time.sleep(10)
  554. tools.text_to_clipboards("")
  555. except Exception, e:
  556. self.error(e)
  557. else:
  558. print ("Can't copy to clipboard, no xsel found in the system!")
  559. def do_open(self, args):
  560. ids = self.get_ids(args)
  561. if not args:
  562. self.help_open()
  563. return
  564. if len(ids) > 1:
  565. print ("Can open only 1 link at a time ...")
  566. return None
  567. try:
  568. node = self._db.getnodes(ids)
  569. url = node[0].url
  570. tools.open_url(url)
  571. except Exception, e:
  572. self.error(e)
  573. def do_edit(self, arg):
  574. ids = self.get_ids(arg)
  575. for i in ids:
  576. try:
  577. i = int(i)
  578. node = self._db.getnodes([i])[0]
  579. menu = CliMenu()
  580. print ("Editing node %d." % (i))
  581. menu.add(CliMenuItem("Username", self.get_username,
  582. node.username,
  583. node.username))
  584. menu.add(CliMenuItem("Password", self.get_password,
  585. node.password,
  586. node.password))
  587. menu.add(CliMenuItem("Url", self.get_url,
  588. node.url,
  589. node.url))
  590. menunotes = CliMenuItem("Notes", self.get_notes,
  591. node.notes,
  592. node.notes)
  593. menu.add(menunotes)
  594. menu.add(CliMenuItem("Tags", self.get_tags,
  595. node.tags,
  596. node.tags))
  597. menu.runner(node)
  598. self._db.editnode(i, node)
  599. # when done with node erase it
  600. zerome(node._password)
  601. except Exception, e:
  602. self.error(e)
  603. def print_node(self, node):
  604. width = str(tools._defaultwidth)
  605. print ("Node %d." % (node._id))
  606. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  607. node.username))
  608. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  609. node.password))
  610. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  611. node.url))
  612. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  613. node.notes))
  614. print (tools.typeset("Tags: ", Fore.RED)),
  615. for t in node.tags:
  616. print (" %s " % t)
  617. print()
  618. def heardEnter():
  619. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  620. for s in i:
  621. if s == sys.stdin:
  622. sys.stdin.readline()
  623. return True
  624. return False
  625. def waituntil_enter(somepredicate, timeout, period=0.25):
  626. mustend = time.time() + timeout
  627. while time.time() < mustend:
  628. cond = somepredicate()
  629. if cond:
  630. break
  631. time.sleep(period)
  632. self.do_cls('')
  633. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  634. if flushtimeout > 0:
  635. print ("Type Enter to flush screen (autoflash in "
  636. "%d sec.)" % flushtimeout)
  637. waituntil_enter(heardEnter, flushtimeout)
  638. def do_tags(self, arg):
  639. enc = CryptoEngine.get()
  640. if not enc.alive():
  641. enc._getcipher()
  642. print ("Tags: \n",)
  643. t = self._tags(enc)
  644. print ('\n'.join(t))
  645. def get_tags(self, default=None, reader=raw_input):
  646. """read tags from user"""
  647. defaultstr = ''
  648. if default:
  649. for t in default:
  650. defaultstr += "%s " % (t)
  651. else:
  652. # tags = self._db.currenttags()
  653. tags = self._db._filtertags
  654. for t in tags:
  655. defaultstr += "%s " % (t)
  656. # strings = []
  657. tags = self._db.listtags(True)
  658. #for t in tags:
  659. # strings.append(t.get_name())
  660. # strings.append(t)
  661. strings = [t for t in tags]
  662. def complete(text, state):
  663. count = 0
  664. for s in strings:
  665. if s.startswith(text):
  666. if count == state:
  667. return s
  668. else:
  669. count += 1
  670. taglist = tools.getinput("Tags: ", defaultstr, completer=complete,
  671. reader=reader)
  672. tagstrings = taglist.split()
  673. tags = [TagN(tn) for tn in tagstrings]
  674. return tags
  675. def do_list(self, args):
  676. if len(args.split()) > 0:
  677. self.do_clear('')
  678. self.do_filter(args)
  679. try:
  680. if sys.platform != 'win32':
  681. rows, cols = tools.gettermsize()
  682. else:
  683. rows, cols = 18, 80 # fix this !
  684. nodeids = self._db.listnodes()
  685. nodes = self._db.getnodes(nodeids)
  686. cols -= 8
  687. i = 0
  688. for n in nodes:
  689. tags = n.tags
  690. tags = filter(None, tags)
  691. tagstring = ''
  692. first = True
  693. for t in tags:
  694. if not first:
  695. tagstring += ", "
  696. else:
  697. first = False
  698. tagstring += t
  699. name = "%s@%s" % (n.username, n.url)
  700. name_len = cols * 2 / 3
  701. tagstring_len = cols / 3
  702. if len(name) > name_len:
  703. name = name[:name_len - 3] + "..."
  704. if len(tagstring) > tagstring_len:
  705. tagstring = tagstring[:tagstring_len - 3] + "..."
  706. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  707. formatted_entry = tools.typeset(fmt % (n._id,
  708. name, tagstring),
  709. Fore.YELLOW, False)
  710. print (formatted_entry)
  711. i += 1
  712. if i > rows - 2:
  713. i = 0
  714. c = tools.getonechar("Press <Space> for more,"
  715. " or 'Q' to cancel")
  716. if c == 'q':
  717. break
  718. except Exception, e:
  719. self.error(e)
  720. def do_filter(self, args):
  721. tagstrings = args.split()
  722. try:
  723. tags = []
  724. for ts in tagstrings:
  725. tags.append(TagN(ts))
  726. self._db.filter(tags)
  727. tags = self._db.currenttags()
  728. print ("Current tags: ",)
  729. if len(tags) == 0:
  730. print ("None",)
  731. for t in tags:
  732. print ("%s " % (t.name),)
  733. print
  734. except Exception, e:
  735. self.error(e)
  736. def do_new(self, args):
  737. """
  738. can override default config settings the following way:
  739. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  740. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  741. Password (Blank to generate):
  742. """
  743. errmsg = ("could not parse config override, please input some"
  744. " kind of dictionary, e.g.: n {'leetify':False, "
  745. " numerics':True, 'special_chars':True}")
  746. try:
  747. username = self.get_username()
  748. if args:
  749. try:
  750. args = ast.literal_eval(args)
  751. except Exception:
  752. raise Exception(errmsg)
  753. if not isinstance(args, dict):
  754. raise Exception(errmsg)
  755. password = self.get_password(1, **args)
  756. else:
  757. numerics = config.get_value(
  758. "Generator", "numerics").lower() == 'true'
  759. # TODO: allow custom leetifying through the config
  760. leetify = config.get_value(
  761. "Generator", "leetify").lower() == 'true'
  762. special_chars = config.get_value(
  763. "Generator", "special_chars").lower() == 'true'
  764. password = self.get_password(0,
  765. numerics=numerics,
  766. symbols=leetify,
  767. special_signs=special_chars)
  768. url = self.get_url()
  769. notes = self.get_notes()
  770. node = NewNode(username, password, url, notes)
  771. node.tags = self.get_tags()
  772. self._db.addnodes([node])
  773. print ("Password ID: %d" % (node._id))
  774. # when done with node erase it
  775. zerome(password)
  776. except Exception, e:
  777. self.error(e)
  778. def do_print(self, arg):
  779. for i in self.get_ids(arg):
  780. try:
  781. node = self._db.getnodes([i])
  782. self.print_node(node[0])
  783. # when done with node erase it
  784. zerome(node[0]._password)
  785. except Exception, e:
  786. self.error(e)
  787. def do_delete(self, arg):
  788. ids = self.get_ids(arg)
  789. try:
  790. nodes = self._db.getnodes(ids)
  791. for n in nodes:
  792. try:
  793. b = tools.getyesno(("Are you sure you want to"
  794. " delete '%s@%s'?"
  795. ) % (n.username, n.url), False)
  796. except NameError:
  797. pass
  798. if b is True:
  799. self._db.removenodes([n])
  800. print ("%s@%s deleted" % (n.username, n.url))
  801. except Exception, e:
  802. self.error(e)
  803. class Aliases(BaseCommands, PwmanCliOld):
  804. """
  805. Define all the alias you want here...
  806. """
  807. def do_cp(self, args):
  808. self.do_copy(args)
  809. def do_e(self, arg):
  810. self.do_edit(arg)
  811. def do_EOF(self, args):
  812. return self.do_exit(args)
  813. def do_l(self, args):
  814. self.do_list(args)
  815. def do_ls(self, args):
  816. self.do_list(args)
  817. def do_p(self, arg):
  818. self.do_print(arg)
  819. def do_rm(self, arg):
  820. self.do_delete(arg)
  821. def do_o(self, args):
  822. self.do_open(args)
  823. def do_h(self, arg):
  824. self.do_help(arg)
  825. def do_n(self, arg):
  826. self.do_new(arg)
  827. class PwmanCliNew(Aliases, BaseCommands):
  828. """
  829. Inherit from the BaseCommands and Aliases
  830. """
  831. def __init__(self, db, hasxsel):
  832. """
  833. initialize CLI interface, set up the DB
  834. connecion, see if we have xsel ...
  835. """
  836. cmd.Cmd.__init__(self)
  837. self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version,
  838. pwman.website)
  839. self._historyfile = config.get_value("Readline", "history")
  840. self.hasxsel = hasxsel
  841. try:
  842. enc = CryptoEngine.get()
  843. #enc.set_callback(CLICallback())
  844. enc._callback = CLICallback()
  845. self._db = db
  846. self._db.open()
  847. except Exception, e:
  848. self.error(e)
  849. sys.exit(1)
  850. try:
  851. readline.read_history_file(self._historyfile)
  852. except IOError, e:
  853. pass
  854. self.prompt = "pwman> "