base.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2013 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. # pylint: disable=I0011
  20. """
  21. Define the base CLI interface for pwman3
  22. """
  23. from __future__ import print_function
  24. class HelpUI(object):
  25. """
  26. this class holds all the UI help functionality.
  27. in PwmanCliNew. The later inherits from this class
  28. and allows it to print help messages to the console.
  29. """
  30. def usage(self, string):
  31. print ("Usage: %s" % (string))
  32. def help_open(self):
  33. self.usage("open <ID>")
  34. print ("Launch default browser with 'xdg-open url',\n",
  35. "the url must contain http:// or https://.")
  36. def help_o(self):
  37. self.help_open()
  38. def help_copy(self):
  39. self.usage("copy <ID>")
  40. print ("Copy password to X clipboard (xsel required)")
  41. def help_cp(self):
  42. self.help_copy()
  43. def help_cls(self):
  44. self.usage("cls")
  45. print ("Clear the Screen from information.")
  46. def help_list(self):
  47. self.usage("list <tag> ...")
  48. print ("List nodes that match current or specified filter.",
  49. " l is an alias.")
  50. def help_EOF(self):
  51. self.help_exit()
  52. def help_delete(self):
  53. self.usage("delete <ID|tag> ...")
  54. print ("Deletes nodes. rm is an alias.")
  55. self._mult_id_help()
  56. def help_h(self):
  57. self.help_help()
  58. def help_help(self):
  59. self.usage("help [topic]")
  60. print ("Prints a help message for a command.")
  61. def help_e(self):
  62. self.help_edit()
  63. def help_n(self):
  64. self.help_new()
  65. def help_p(self):
  66. self.help_print()
  67. def help_l(self):
  68. self.help_list()
  69. def help_edit(self):
  70. self.usage("edit <ID|tag> ... ")
  71. print ("Edits a nodes.")
  72. self._mult_id_help()
  73. def help_import(self):
  74. self.usage("import [filename] ...")
  75. print ("Imports a nodes from a file.")
  76. def help_export(self):
  77. self.usage("export <ID|tag> ... ")
  78. print ("Exports a list of ids to an external format. If no IDs or",
  79. " tags are specified, then all nodes under the current",
  80. " filter are exported.")
  81. self._mult_id_help()
  82. def help_new(self):
  83. self.usage("new")
  84. print ("Creates a new node.,",
  85. "You can override default config settings the following way:\n",
  86. "pwman> n {'leetify':False, 'numerics':True}")
  87. def help_rm(self):
  88. self.help_delete()
  89. def help_print(self):
  90. self.usage("print <ID|tag> ...")
  91. print ("Displays a node. ")
  92. self._mult_id_help()
  93. def _mult_id_help(self):
  94. print("Multiple ids and nodes can be specified, separated by a space.",
  95. " A range of ids can be specified in the format n-N. e.g. ",
  96. " '10-20' would specify all nodes having ids from 10 to 20 ",
  97. " inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar'",
  98. " would yield to all nodes with tag 'foo', node 2 and all ",
  99. " nodes with tag 'bar'.")
  100. def help_exit(self):
  101. self.usage("exit")
  102. print("Exits the application.")
  103. def help_save(self):
  104. self.usage("save [filename]")
  105. print("Saves the current configuration to [filename]. If no filename ",
  106. "is given, the configuration is saved to the file from which ",
  107. "the initial configuration was loaded.")
  108. def help_set(self):
  109. self.usage("set [configoption] [value]")
  110. print("Sets a configuration option. If no value is specified, the ",
  111. "current value for [configoption] is output. If neither ",
  112. "[configoption] nor [value] are specified, the whole current ",
  113. "configuration is output. [configoption] must be of the ",
  114. "format <section>.<option>")
  115. def help_passwd(self):
  116. self.usage("passwd")
  117. print("Changes the password on the database. ")
  118. def help_forget(self):
  119. self.usage("forget")
  120. print("Forgets the database password. Your password will need to ",
  121. "be reentered before accessing the database again.")
  122. def help_clear(self):
  123. self.usage("clear")
  124. print("Clears the filter criteria. ")
  125. def help_filter(self):
  126. self.usage("filter <tag> ...")
  127. print("Filters nodes on tag. Arguments can be zero or more tags. ",
  128. "Displays current tags if called without arguments.")
  129. def help_tags(self):
  130. self.usage("tags")
  131. print("Displays all tags in used in the database.")
  132. class BaseUI(object):
  133. """
  134. this class holds all the UI functionality
  135. in PwmanCliNew. The later inherits from this class
  136. and allows it to print messages to the console.
  137. """
  138. def _do_filter(self, args):
  139. pass
  140. def _tags(self, enc):
  141. """
  142. read tags from TAGS table in DB,
  143. this method has a working unittest
  144. """
  145. tags = self._db.listtags()
  146. if tags:
  147. _tags = [''] * len(tags)
  148. for t in tags:
  149. try:
  150. _tags.append(enc.decrypt(t))
  151. except (ValueError, Exception), e:
  152. _tags.append(t)
  153. del(e)
  154. _tags = filter(None, _tags)
  155. return _tags
  156. import pwman.exchange.importer as importer
  157. from pwman.data.nodes import Node
  158. from pwman.util.crypto import CryptoEngine
  159. from pwman.util.crypto import zerome
  160. import pwman.util.config as config
  161. import re
  162. import sys
  163. import os
  164. import time
  165. import select as uselect
  166. import ast
  167. from pwman.ui import tools
  168. from pwman.ui.tools import CliMenu
  169. from pwman.ui.tools import CliMenuItem
  170. from colorama import Fore
  171. from pwman.data.nodes import NewNode
  172. from pwman.ui.tools import CMDLoop
  173. import getpass
  174. from pwman.data.tags import TagNew
  175. try:
  176. import readline
  177. _readline_available = True
  178. except ImportError, e: # pragma: no cover
  179. _readline_available = False
  180. def get_pass_conf():
  181. numerics = config.get_value("Generator", "numerics").lower() == 'true'
  182. # TODO: allow custom leetifying through the config
  183. leetify = config.get_value("Generator", "leetify").lower() == 'true'
  184. special_chars = config.get_value("Generator", "special_chars"
  185. ).lower() == 'true'
  186. return numerics, leetify, special_chars
  187. # pylint: disable=R0904
  188. class PwmanCliOld(HelpUI, BaseUI):
  189. def error(self, exception):
  190. if (isinstance(exception, KeyboardInterrupt)):
  191. print('')
  192. else:
  193. print("Error: {0} ".format(exception))
  194. def do_exit(self, args):
  195. """exit the ui"""
  196. self._db.close()
  197. return True
  198. def get_ids(self, args):
  199. """
  200. Command can get a single ID or
  201. a range of IDs, with begin-end.
  202. e.g. 1-3 , will get 1 to 3.
  203. """
  204. ids = []
  205. rex = re.compile("^(?P<begin>\d+)(?:-(?P<end>\d+))?$")
  206. rex = rex.match(args)
  207. if hasattr(rex, 'groupdict'):
  208. try:
  209. begin = int(rex.groupdict()['begin'])
  210. end = int(rex.groupdict()['end'])
  211. if not end > begin:
  212. print("Start node should be smaller than end node")
  213. return ids
  214. ids += range(begin, end+1)
  215. return ids
  216. except TypeError:
  217. ids.append(int(begin))
  218. else:
  219. print("Could not understand your input...")
  220. return ids
  221. def get_username(self, default="", reader=raw_input):
  222. return tools.getinput("Username: ", default, reader)
  223. def get_url(self, default="", reader=raw_input):
  224. return tools.getinput("Url: ", default, reader)
  225. def get_notes(self, default="", reader=raw_input):
  226. return tools.getinput("Notes: ", default, reader)
  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. print('Not implemented...')
  280. def do_new(self, args):
  281. """
  282. can override default config settings the following way:
  283. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  284. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  285. Password (Blank to generate):
  286. """
  287. errmsg = ("could not parse config override, please input some"
  288. " kind of dictionary, e.g.: n {'leetify':False, "
  289. " numerics':True, 'special_chars':True}")
  290. try:
  291. username = self.get_username()
  292. if args:
  293. try:
  294. args = ast.literal_eval(args)
  295. except Exception:
  296. raise Exception(errmsg)
  297. if not isinstance(args, dict):
  298. raise Exception(errmsg)
  299. password = self.get_password(1, **args)
  300. else:
  301. numerics = config.get_value("Generator",
  302. "numerics").lower() == 'true'
  303. # TODO: allow custom leetifying through the config
  304. leetify = config.get_value("Generator",
  305. "leetify").lower() == 'true'
  306. special_chars = config.get_value("Generator",
  307. "special_chars").lower() == \
  308. 'true'
  309. password = self.get_password(0,
  310. numerics=numerics,
  311. symbols=leetify,
  312. special_signs=special_chars)
  313. url = self.get_url()
  314. notes = self.get_notes()
  315. node = Node(username, password, url, notes)
  316. tags = self.get_tags()
  317. node.set_tags(tags)
  318. self._db.addnodes([node])
  319. print ("Password ID: %d" % (node.get_id()))
  320. except Exception, e:
  321. self.error(e)
  322. def do_print(self, arg):
  323. for i in self.get_ids(arg):
  324. try:
  325. node = self._db.getnodes([i])
  326. self.print_node(node[0])
  327. except Exception, e: # pragma: no cover
  328. self.error(e)
  329. def do_delete(self, arg):
  330. ids = self.get_ids(arg)
  331. try:
  332. nodes = self._db.getnodes(ids)
  333. for n in nodes:
  334. b = tools.getyesno("Are you sure you want to delete '%s@%s'?"
  335. % (n.get_username(), n.get_url()), False)
  336. if b is True:
  337. self._db.removenodes([n])
  338. print ("%s@%s deleted" % (n.get_username(), n.get_url()))
  339. except Exception, e:
  340. self.error(e)
  341. def do_list(self, args):
  342. """
  343. TODO: in order to make this code testable
  344. The functionality in this method should
  345. go to a method that returns a string.
  346. This method should only do the printing.
  347. """
  348. if len(args.split()) > 0:
  349. self.do_clear('')
  350. self.do_filter(args)
  351. try:
  352. if sys.platform != 'win32':
  353. rows, cols = tools.gettermsize()
  354. else:
  355. rows, cols = 18, 80
  356. nodeids = self._db.listnodes()
  357. nodes = self._db.getnodes(nodeids)
  358. cols -= 8
  359. i = 0
  360. for n in nodes:
  361. tags = n.get_tags()
  362. tagstring = ''
  363. first = True
  364. for t in tags:
  365. if not first:
  366. tagstring += ", "
  367. else:
  368. first = False
  369. tagstring += t.get_name()
  370. name = "%s@%s" % (n.get_username(), n.get_url())
  371. name_len = cols * 2 / 3
  372. tagstring_len = cols / 3
  373. if len(name) > name_len:
  374. name = name[:name_len - 3] + "..."
  375. if len(tagstring) > tagstring_len:
  376. tagstring = tagstring[:tagstring_len - 3] + "..."
  377. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  378. print (tools.typeset(fmt % (n.get_id(), name, tagstring),
  379. Fore.YELLOW, False))
  380. i += 1
  381. if i > rows - 2:
  382. i = 0
  383. c = tools.getonechar("Press <Space> for more, "
  384. "or 'Q' to cancel")
  385. if c == 'q':
  386. break
  387. except Exception, e:
  388. self.error(e)
  389. def do_forget(self, args):
  390. try:
  391. enc = CryptoEngine.get()
  392. enc.forget()
  393. except Exception, e:
  394. self.error(e)
  395. def do_passwd(self, args):
  396. try:
  397. key = self._db.changepassword()
  398. self._db._save(key)
  399. except Exception, e:
  400. self.error(e)
  401. def do_set(self, args):
  402. argstrs = args.split()
  403. try:
  404. if len(argstrs) == 0:
  405. conf = config.get_conf()
  406. for s in conf.keys():
  407. for n in conf[s].keys():
  408. print ("%s.%s = %s" % (s, n, conf[s][n]))
  409. elif len(argstrs) == 1:
  410. r = re.compile("(.+)\.(.+)")
  411. m = r.match(argstrs[0])
  412. if m is None or len(m.groups()) != 2:
  413. print ("Invalid option format")
  414. self.help_set()
  415. return
  416. print ("%s.%s = %s" % (m.group(1), m.group(2),
  417. config.get_value(m.group(1),
  418. m.group(2))))
  419. elif len(argstrs) == 2:
  420. r = re.compile("(.+)\.(.+)")
  421. m = r.match(argstrs[0])
  422. if m is None or len(m.groups()) != 2:
  423. print ("Invalid option format")
  424. self.help_set()
  425. return
  426. config.set_value(m.group(1), m.group(2), argstrs[1])
  427. else:
  428. self.help_set()
  429. except Exception, e:
  430. self.error(e)
  431. def do_save(self, args):
  432. argstrs = args.split()
  433. try:
  434. if len(argstrs) > 0:
  435. config.save(argstrs[0])
  436. else:
  437. config.save()
  438. print ("Config saved.")
  439. except Exception, e:
  440. self.error(e)
  441. def do_cls(self, args):
  442. os.system('clear')
  443. def do_copy(self, args):
  444. if self.hasxsel:
  445. ids = self.get_ids(args)
  446. if len(ids) > 1:
  447. print ("Can copy only 1 password at a time...")
  448. return None
  449. try:
  450. node = self._db.getnodes(ids)
  451. tools.text_to_clipboards(node[0].get_password())
  452. print ("copied password for {}@{} clipboard".format(
  453. node[0].get_username(), node[0].get_url()))
  454. print ("erasing in 10 sec...")
  455. time.sleep(10)
  456. tools.text_to_clipboards("")
  457. except Exception, e:
  458. self.error(e)
  459. else:
  460. print ("Can't copy to clipboard, no xsel found in the system!")
  461. def do_open(self, args):
  462. ids = self.get_ids(args)
  463. if not args:
  464. self.help_open()
  465. return
  466. if len(ids) > 1:
  467. print ("Can open only 1 link at a time ...")
  468. return None
  469. try:
  470. node = self._db.getnodes(ids)
  471. url = node[0].get_url()
  472. tools.open_url(url)
  473. except Exception, e:
  474. self.error(e)
  475. def postloop(self):
  476. try:
  477. readline.write_history_file(self._historyfile)
  478. except Exception:
  479. pass
  480. def __init__(self, db, hasxsel):
  481. """
  482. initialize CLI interface, set up the DB
  483. connecion, see if we have xsel ...
  484. """
  485. _dbwarning = "\n*** WARNNING: You are using the old database format" \
  486. + " which is unsecure." \
  487. + " This database format is in hold. No bugs are fixed. Please " \
  488. + " upgrade your database." \
  489. + " Check the help (pwman3 -h) or look at the manpage which" \
  490. + " explains how to proceed. ***"
  491. print (_dbwarning)
  492. sys.exit(1)
  493. class BaseCommands(PwmanCliOld):
  494. """
  495. Inherit from the old class, override
  496. all the methods related to tags, and
  497. newer Node format, so backward compatability is kept...
  498. Commands defined here, can have aliases definded in Aliases.
  499. You can define the aliases here too, but it makes
  500. the class code really long and unclear.
  501. """
  502. def do_copy(self, args):
  503. if self.hasxsel:
  504. ids = self.get_ids(args)
  505. if len(ids) > 1:
  506. print ("Can copy only 1 password at a time...")
  507. return None
  508. try:
  509. node = self._db.getnodes(ids)
  510. tools.text_to_clipboards(node[0].password)
  511. print ("copied password for {}@{} clipboard".format(
  512. node[0].username, node[0].url))
  513. print ("erasing in 10 sec...")
  514. time.sleep(10)
  515. tools.text_to_clipboards("")
  516. except Exception, e:
  517. self.error(e)
  518. else:
  519. print ("Can't copy to clipboard, no xsel found in the system!")
  520. def do_open(self, args):
  521. ids = self.get_ids(args)
  522. if not args:
  523. self.help_open()
  524. return
  525. if len(ids) > 1:
  526. print ("Can open only 1 link at a time ...")
  527. return None
  528. try:
  529. node = self._db.getnodes(ids)
  530. url = node[0].url
  531. tools.open_url(url)
  532. except Exception, e:
  533. self.error(e)
  534. def do_edit(self, arg, menu=None):
  535. ids = self.get_ids(arg)
  536. for i in ids:
  537. try:
  538. i = int(i)
  539. node = self._db.getnodes([i])[0]
  540. if not menu:
  541. menu = CMDLoop()
  542. print ("Editing node %d." % (i))
  543. menu.add(CliMenuItem("Username", self.get_username,
  544. node.username,
  545. node.username))
  546. menu.add(CliMenuItem("Password", self.get_password,
  547. node.password,
  548. node.password))
  549. menu.add(CliMenuItem("Url", self.get_url,
  550. node.url,
  551. node.url))
  552. menunotes = CliMenuItem("Notes", self.get_notes,
  553. node.notes,
  554. node.notes)
  555. menu.add(menunotes)
  556. menu.add(CliMenuItem("Tags", self.get_tags,
  557. node.tags,
  558. node.tags))
  559. menu.run(node)
  560. self._db.editnode(i, node)
  561. # when done with node erase it
  562. zerome(node._password)
  563. except Exception, e:
  564. self.error(e)
  565. def print_node(self, node):
  566. width = str(tools._defaultwidth)
  567. print ("Node %d." % (node._id))
  568. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  569. node.username))
  570. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  571. node.password))
  572. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  573. node.url))
  574. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  575. node.notes))
  576. print (tools.typeset("Tags: ", Fore.RED)),
  577. for t in node.tags:
  578. print (" %s " % t)
  579. print()
  580. def heardEnter():
  581. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  582. for s in i:
  583. if s == sys.stdin:
  584. sys.stdin.readline()
  585. return True
  586. return False
  587. def waituntil_enter(somepredicate, timeout, period=0.25):
  588. mustend = time.time() + timeout
  589. while time.time() < mustend:
  590. cond = somepredicate()
  591. if cond:
  592. break
  593. time.sleep(period)
  594. self.do_cls('')
  595. try:
  596. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  597. except ValueError:
  598. flushtimeout = 10
  599. if flushtimeout > 0:
  600. print ("Type Enter to flush screen (autoflash in "
  601. "%d sec.)" % flushtimeout)
  602. waituntil_enter(heardEnter, flushtimeout)
  603. def do_tags(self, arg):
  604. enc = CryptoEngine.get()
  605. if not enc.alive():
  606. enc._getcipher()
  607. print ("Tags: \n",)
  608. t = self._tags(enc)
  609. print ('\n'.join(t))
  610. def get_tags(self, default=None, reader=raw_input):
  611. """read tags from user"""
  612. defaultstr = ''
  613. if default:
  614. for t in default:
  615. defaultstr += "%s " % (t)
  616. else:
  617. # tags = self._db.currenttags()
  618. tags = self._db._filtertags
  619. for t in tags:
  620. defaultstr += "%s " % (t)
  621. # strings = []
  622. tags = self._db.listtags(True)
  623. # for t in tags:
  624. # strings.append(t.get_name())
  625. # strings.append(t)
  626. strings = [t for t in tags]
  627. def complete(text, state):
  628. count = 0
  629. for s in strings:
  630. if s.startswith(text):
  631. if count == state:
  632. return s
  633. else:
  634. count += 1
  635. taglist = tools.getinput("Tags: ", defaultstr, completer=complete,
  636. reader=reader)
  637. tagstrings = taglist.split()
  638. tags = [TagNew(tn) for tn in tagstrings]
  639. return tags
  640. def do_list(self, args):
  641. if len(args.split()) > 0:
  642. self.do_clear('')
  643. self.do_filter(args)
  644. try:
  645. if sys.platform != 'win32':
  646. rows, cols = tools.gettermsize()
  647. else:
  648. rows, cols = 18, 80 # fix this !
  649. nodeids = self._db.listnodes()
  650. nodes = self._db.getnodes(nodeids)
  651. cols -= 8
  652. i = 0
  653. for n in nodes:
  654. tags = n.tags
  655. tags = filter(None, tags)
  656. tagstring = ''
  657. first = True
  658. for t in tags:
  659. if not first:
  660. tagstring += ", "
  661. else:
  662. first = False
  663. tagstring += t
  664. name = "%s@%s" % (n.username, n.url)
  665. name_len = cols * 2 / 3
  666. tagstring_len = cols / 3
  667. if len(name) > name_len:
  668. name = name[:name_len - 3] + "..."
  669. if len(tagstring) > tagstring_len:
  670. tagstring = tagstring[:tagstring_len - 3] + "..."
  671. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  672. formatted_entry = tools.typeset(fmt % (n._id,
  673. name, tagstring),
  674. Fore.YELLOW, False)
  675. print (formatted_entry)
  676. i += 1
  677. if i > rows - 2:
  678. i = 0
  679. c = tools.getonechar("Press <Space> for more,"
  680. " or 'Q' to cancel")
  681. if c.lower() == 'q':
  682. break
  683. except Exception, e:
  684. self.error(e)
  685. def do_filter(self, args):
  686. tagstrings = args.split()
  687. try:
  688. tags = [TagNew(ts) for ts in tagstrings]
  689. self._db.filter(tags)
  690. tags = self._db.currenttags()
  691. print ("Current tags: ",)
  692. if len(tags) == 0:
  693. print ("None",)
  694. for t in tags:
  695. print ("%s " % t)
  696. print
  697. except Exception, e:
  698. self.error(e)
  699. def do_new(self, args):
  700. """
  701. can override default config settings the following way:
  702. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  703. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  704. Password (Blank to generate):
  705. """
  706. errmsg = ("could not parse config override, please input some"
  707. " kind of dictionary, e.g.: n {'leetify':False, "
  708. " numerics':True, 'special_chars':True}")
  709. try:
  710. username = self.get_username()
  711. if args:
  712. try:
  713. args = ast.literal_eval(args)
  714. except Exception:
  715. raise Exception(errmsg)
  716. if not isinstance(args, dict):
  717. raise Exception(errmsg)
  718. password = self.get_password(argsgiven=1, **args)
  719. else:
  720. numerics, leet, s_chars = get_pass_conf()
  721. password = self.get_password(argsgiven=0,
  722. numerics=numerics,
  723. symbols=leet,
  724. special_signs=s_chars)
  725. url = self.get_url()
  726. notes = self.get_notes()
  727. node = NewNode()
  728. node.username = username
  729. node.password = password
  730. node.url = url
  731. node.notes = notes
  732. #node = NewNode(username, password, url, notes)
  733. node.tags = self.get_tags()
  734. self._db.addnodes([node])
  735. print ("Password ID: %d" % (node._id))
  736. # when done with node erase it
  737. zerome(password)
  738. except Exception, e:
  739. self.error(e)
  740. def do_print(self, arg):
  741. for i in self.get_ids(arg):
  742. try:
  743. node = self._db.getnodes([i])
  744. self.print_node(node[0])
  745. # when done with node erase it
  746. zerome(node[0]._password)
  747. except Exception, e:
  748. self.error(e)
  749. def do_delete(self, arg):
  750. ids = self.get_ids(arg)
  751. try:
  752. nodes = self._db.getnodes(ids)
  753. for n in nodes:
  754. try:
  755. b = tools.getyesno(("Are you sure you want to"
  756. " delete '%s@%s'?"
  757. ) % (n.username, n.url), False)
  758. except NameError:
  759. pass
  760. if b is True:
  761. self._db.removenodes([n])
  762. print ("%s@%s deleted" % (n.username, n.url))
  763. except Exception, e:
  764. self.error(e)
  765. def get_password(self, argsgiven, numerics=False, leetify=False,
  766. symbols=False, special_signs=False,
  767. reader=getpass.getpass, length=None):
  768. return tools.getpassword("Password (Blank to generate): ",
  769. reader=reader, length=length, leetify=leetify)
  770. class Aliases(BaseCommands, PwmanCliOld):
  771. """
  772. Define all the alias you want here...
  773. """
  774. def do_cp(self, args):
  775. self.do_copy(args)
  776. def do_e(self, arg):
  777. self.do_edit(arg)
  778. def do_EOF(self, args):
  779. return self.do_exit(args)
  780. def do_l(self, args):
  781. self.do_list(args)
  782. def do_ls(self, args):
  783. self.do_list(args)
  784. def do_p(self, arg):
  785. self.do_print(arg)
  786. def do_rm(self, arg):
  787. self.do_delete(arg)
  788. def do_o(self, args):
  789. self.do_open(args)
  790. def do_h(self, arg):
  791. self.do_help(arg)
  792. def do_n(self, arg):
  793. self.do_new(arg)