cli.py 33 KB

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