cli.py 32 KB

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