cli.py 33 KB

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