cli.py 32 KB

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