cli.py 33 KB

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