cli.py 33 KB

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