cli.py 32 KB

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