ocli.py 33 KB

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