cli.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. try:
  49. import readline
  50. _readline_available = True
  51. except ImportError, e:
  52. _readline_available = False
  53. # pylint: disable=R0904
  54. class PwmanCli(cmd.Cmd):
  55. """
  56. UI class for MacOSX
  57. """
  58. def error(self, exception):
  59. if (isinstance(exception, KeyboardInterrupt)):
  60. print
  61. else:
  62. # traceback.print_exc()
  63. print "Error: %s " % (exception)
  64. def do_EOF(self, args):
  65. return self.do_exit(args)
  66. def do_exit(self, args):
  67. """exit the ui"""
  68. print
  69. # try:
  70. # print "goodbye"
  71. self._db.close()
  72. # except DatabaseException, e:
  73. # self.error(e)
  74. return True
  75. def get_ids(self, args):
  76. ids = []
  77. rex = re.compile(r"^(\d+)-(\d+)$")
  78. idstrs = args.split()
  79. for i in idstrs:
  80. m = rex.match(i)
  81. if m is None:
  82. try:
  83. ids.append(int(i))
  84. except ValueError:
  85. self._db.clearfilter()
  86. self._db.filter([Tag(i)])
  87. ids += self._db.listnodes()
  88. else:
  89. ids += range(int(m.group(1)),
  90. int(m.group(2))+1)
  91. return ids
  92. def get_filesystem_path(self, default=""):
  93. return tools.getinput("Enter filename: ", default)
  94. def get_username(self, default=""):
  95. return tools.getinput("Username: ", default)
  96. def get_password(self, argsgiven, numerics=False, leetify=False,
  97. symbols=False, special_signs=False):
  98. """
  99. in the config file:
  100. numerics -> numerics
  101. leetify -> symbols
  102. special_chars -> special_signs
  103. """
  104. if argsgiven == 1:
  105. length = tools.getinput("Password length (default 7): ", "7")
  106. length = len(length)
  107. password, dumpme = generator.generate_password(length, length,
  108. True, leetify,
  109. numerics,
  110. special_signs)
  111. print "New password: %s" % (password)
  112. return password
  113. # no args given
  114. password = tools.getpassword("Password (Blank to generate): ",
  115. tools._defaultwidth, False)
  116. if len(password) == 0:
  117. length = tools.getinput("Password length (default 7): ", "7")
  118. if length:
  119. length = int(length)
  120. else:
  121. length = 7
  122. password, dumpme = generator.generate_password(length, length,
  123. True, leetify,
  124. numerics,
  125. special_signs)
  126. print "New password: %s" % (password)
  127. return password
  128. def get_url(self, default=""):
  129. return tools.getinput("Url: ", default)
  130. def get_notes(self, default=""):
  131. return tools.getinput("Notes: ", default)
  132. def get_tags(self, default=None):
  133. defaultstr = ''
  134. if default:
  135. for t in default:
  136. defaultstr += "%s " % (t.get_name())
  137. else:
  138. tags = self._db.currenttags()
  139. for t in tags:
  140. defaultstr += "%s " % (t.get_name())
  141. strings = []
  142. tags = self._db.listtags(True)
  143. for t in tags:
  144. strings.append(t.get_name())
  145. def complete(text, state):
  146. count = 0
  147. for s in strings:
  148. if s.startswith(text):
  149. if count == state:
  150. return s
  151. else:
  152. count += 1
  153. taglist = tools.getinput("Tags: ", defaultstr, complete)
  154. tagstrings = taglist.split()
  155. tags = []
  156. for tn in tagstrings:
  157. tags.append(Tag(tn))
  158. return tags
  159. def print_node(self, node):
  160. width = str(tools._defaultwidth)
  161. print "Node %d." % (node._id)
  162. print ("%"+width+"s %s") % (tools.typeset("Username:", Fore.RED),
  163. node.get_username())
  164. print ("%"+width+"s %s") % (tools.typeset("Password:", Fore.RED),
  165. node.get_password())
  166. print ("%"+width+"s %s") % (tools.typeset("Url:", Fore.RED),
  167. node.get_url())
  168. print ("%"+width+"s %s") % (tools.typeset("Notes:", Fore.RED),
  169. node.get_notes())
  170. print tools.typeset("Tags: ", Fore.RED),
  171. for t in node.get_tags():
  172. print " %s \n" % t.get_name(),
  173. def heardEnter():
  174. inpt, out, err = uselect.select([sys.stdin], [], [], 0.0001)
  175. for stream in inpt:
  176. if stream == sys.stdin:
  177. sys.stdin.readline()
  178. return True
  179. return False
  180. def waituntil_enter(somepredicate, timeout, period=0.25):
  181. mustend = time.time() + timeout
  182. while time.time() < mustend:
  183. cond = somepredicate()
  184. if cond:
  185. break
  186. time.sleep(period)
  187. self.do_cls('')
  188. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  189. if flushtimeout > 0:
  190. print "Type Enter to flush screen (autoflash in "\
  191. + "%d sec.)" % flushtimeout
  192. waituntil_enter(heardEnter, flushtimeout)
  193. def do_tags(self, arg):
  194. tags = self._db.listtags()
  195. if len(tags) > 0:
  196. tags[0].get_name() # hack to get password request before output
  197. print "Tags: ",
  198. if len(tags) == 0:
  199. print "None",
  200. for t in tags:
  201. print "%s " % (t.get_name()),
  202. print
  203. def complete_filter(self, text, line, begidx, endidx):
  204. strings = []
  205. enc = CryptoEngine.get()
  206. if not enc.alive():
  207. return strings
  208. tags = self._db.listtags()
  209. for t in tags:
  210. name = t.get_name()
  211. if name.startswith(text):
  212. strings.append(t.get_name())
  213. return strings
  214. def do_filter(self, args):
  215. tagstrings = args.split()
  216. try:
  217. tags = []
  218. for ts in tagstrings:
  219. tags.append(Tag(ts))
  220. self._db.filter(tags)
  221. tags = self._db.currenttags()
  222. print "Current tags: ",
  223. if len(tags) == 0:
  224. print "None",
  225. for t in tags:
  226. print "%s " % (t.get_name()),
  227. print
  228. except Exception, e:
  229. self.error(e)
  230. def do_clear(self, args):
  231. try:
  232. self._db.clearfilter()
  233. except Exception, e:
  234. self.error(e)
  235. def do_e(self, arg):
  236. self.do_edit(arg)
  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_h(self, arg):
  311. self.do_help(arg)
  312. def do_n(self, arg):
  313. self.do_new(arg)
  314. def do_new(self, args):
  315. """
  316. can override default config settings the following way:
  317. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  318. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  319. Password (Blank to generate):
  320. """
  321. errmsg = """could not parse config override, please input some"""\
  322. + """ kind of dictionary, e.g.: n {'leetify':False, """\
  323. + """'numerics':True, 'special_chars':True}"""
  324. try:
  325. username = self.get_username()
  326. if args:
  327. try:
  328. args = ast.literal_eval(args)
  329. except Exception:
  330. raise Exception(errmsg)
  331. if not isinstance(args, dict):
  332. raise Exception(errmsg)
  333. password = self.get_password(1, **args)
  334. else:
  335. numerics = config.get_value("Generator",
  336. "numerics").lower() == 'true'
  337. # TODO: allow custom leetifying through the config
  338. leetify = config.get_value("Generator",
  339. "leetify").lower() == 'true'
  340. special_chars = config.get_value("Generator",
  341. "special_chars").lower() == \
  342. 'true'
  343. password = self.get_password(0,
  344. numerics=numerics,
  345. symbols=leetify,
  346. special_signs=special_chars)
  347. url = self.get_url()
  348. notes = self.get_notes()
  349. node = Node(username, password, url, notes)
  350. tags = self.get_tags()
  351. node.set_tags(tags)
  352. self._db.addnodes([node])
  353. print "Password ID: %d" % (node.get_id())
  354. except Exception, e:
  355. self.error(e)
  356. def do_p(self, arg):
  357. self.do_print(arg)
  358. def do_print(self, arg):
  359. for i in self.get_ids(arg):
  360. try:
  361. node = self._db.getnodes([i])
  362. self.print_node(node[0])
  363. except Exception, e:
  364. self.error(e)
  365. def do_rm(self, arg):
  366. self.do_delete(arg)
  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_l(self, args):
  380. self.do_list(args)
  381. def do_ls(self, args):
  382. self.do_list(args)
  383. def do_list(self, args):
  384. if len(args.split()) > 0:
  385. self.do_clear('')
  386. self.do_filter(args)
  387. try:
  388. if sys.platform != 'win32':
  389. rows, cols = tools.gettermsize()
  390. else:
  391. rows, cols = 18, 80
  392. nodeids = self._db.listnodes()
  393. nodes = self._db.getnodes(nodeids)
  394. cols -= 8
  395. i = 0
  396. for n in nodes:
  397. tags = n.get_tags()
  398. tagstring = ''
  399. first = True
  400. for t in tags:
  401. if not first:
  402. tagstring += ", "
  403. else:
  404. first = False
  405. tagstring += t.get_name()
  406. name = "%s@%s" % (n.get_username(), n.get_url())
  407. name_len = cols * 2 / 3
  408. tagstring_len = cols / 3
  409. if len(name) > name_len:
  410. name = name[:name_len-3] + "..."
  411. if len(tagstring) > tagstring_len:
  412. tagstring = tagstring[:tagstring_len-3] + "..."
  413. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  414. print tools.typeset(fmt % (n.get_id(), name, tagstring),
  415. Fore.YELLOW, False)
  416. i += 1
  417. if i > rows-2:
  418. i = 0
  419. c = tools.getonechar("Press <Space> for more, "
  420. "or 'Q' to cancel")
  421. if c == 'q':
  422. break
  423. except Exception, e:
  424. self.error(e)
  425. def do_forget(self, args):
  426. try:
  427. enc = CryptoEngine.get()
  428. enc.forget()
  429. except Exception, e:
  430. self.error(e)
  431. def do_passwd(self, args):
  432. try:
  433. self._db.changepassword()
  434. except Exception, e:
  435. self.error(e)
  436. def do_set(self, args):
  437. argstrs = args.split()
  438. try:
  439. if len(argstrs) == 0:
  440. conf = config.get_conf()
  441. for s in conf.keys():
  442. for n in conf[s].keys():
  443. print "%s.%s = %s" % (s, n, conf[s][n])
  444. elif len(argstrs) == 1:
  445. r = re.compile("(.+)\.(.+)")
  446. m = r.match(argstrs[0])
  447. if m is None or len(m.groups()) != 2:
  448. print "Invalid option format"
  449. self.help_set()
  450. return
  451. print "%s.%s = %s" % (m.group(1), m.group(2),
  452. config.get_value(m.group(1), m.group(2)))
  453. elif len(argstrs) == 2:
  454. r = re.compile("(.+)\.(.+)")
  455. m = r.match(argstrs[0])
  456. if m is None or len(m.groups()) != 2:
  457. print "Invalid option format"
  458. self.help_set()
  459. return
  460. config.set_value(m.group(1), m.group(2), argstrs[1])
  461. else:
  462. self.help_set()
  463. except Exception, e:
  464. self.error(e)
  465. def do_save(self, args):
  466. argstrs = args.split()
  467. try:
  468. if len(argstrs) > 0:
  469. config.save(argstrs[0])
  470. else:
  471. config.save()
  472. print "Config saved."
  473. except Exception, e:
  474. self.error(e)
  475. def do_cls(self, args):
  476. os.system('clear')
  477. def do_copy(self, args):
  478. if self.hasxsel:
  479. ids = self.get_ids(args)
  480. if len(ids) > 1:
  481. print "Can copy only 1 password at a time..."
  482. return None
  483. try:
  484. node = self._db.getnodes(ids)
  485. tools.text_to_clipboards(node[0].get_password())
  486. print "copied password for {}@{} clipboard".format(
  487. node[0].get_username(), node[0].get_url())
  488. print "erasing in 10 sec..."
  489. time.sleep(10)
  490. tools.text_to_clipboards("")
  491. except Exception, e:
  492. self.error(e)
  493. else:
  494. print "Can't copy to clipboard, no xsel found in the system!"
  495. def do_cp(self, args):
  496. self.do_copy(args)
  497. def do_open(self, args):
  498. ids = self.get_ids(args)
  499. if not args:
  500. self.help_open()
  501. return
  502. if len(ids) > 1:
  503. print "Can open only 1 link at a time ..."
  504. return None
  505. try:
  506. node = self._db.getnodes(ids)
  507. url = node[0].get_url()
  508. tools.open_url(url)
  509. except Exception, e:
  510. self.error(e)
  511. def do_o(self, args):
  512. self.do_open(args)
  513. ##
  514. ## Help functions
  515. ##
  516. def usage(self, string):
  517. print "Usage: %s" % (string)
  518. def help_open(self):
  519. self.usage("open <ID>")
  520. print "Launch default browser with 'xdg-open url',\n" \
  521. + "the url must contain http:// or https://."
  522. def help_o(self):
  523. self.help_open()
  524. def help_copy(self):
  525. self.usage("copy <ID>")
  526. print "Copy password to X clipboard (xsel required)"
  527. def help_cp(self):
  528. self.help_copy()
  529. def help_cls(self):
  530. self.usage("cls")
  531. print "Clear the Screen from information."
  532. def help_list(self):
  533. self.usage("list <tag> ...")
  534. print "List nodes that match current or specified filter." \
  535. + " l is an alias."
  536. def help_EOF(self):
  537. self.help_exit()
  538. def help_delete(self):
  539. self.usage("delete <ID|tag> ...")
  540. print "Deletes nodes. rm is an alias."
  541. self._mult_id_help()
  542. def help_h(self):
  543. self.help_help()
  544. def help_help(self):
  545. self.usage("help [topic]")
  546. print "Prints a help message for a command."
  547. def help_e(self):
  548. self.help_edit()
  549. def help_n(self):
  550. self.help_new()
  551. def help_p(self):
  552. self.help_print()
  553. def help_l(self):
  554. self.help_list()
  555. def help_edit(self):
  556. self.usage("edit <ID|tag> ... ")
  557. print "Edits a nodes."
  558. self._mult_id_help()
  559. def help_import(self):
  560. self.usage("import [filename] ...")
  561. print "Imports a nodes from a file."
  562. def help_export(self):
  563. self.usage("export <ID|tag> ... ")
  564. print "Exports a list of ids to an external format. If no IDs or" \
  565. + " tags are specified, then all nodes under the current" \
  566. + " filter are exported."
  567. self._mult_id_help()
  568. def help_new(self):
  569. self.usage("new")
  570. print """Creates a new node.,
  571. You can override default config settings the following way:
  572. pwman> n {'leetify':False, 'numerics':True}"""
  573. def help_rm(self):
  574. self.help_delete()
  575. def help_print(self):
  576. self.usage("print <ID|tag> ...")
  577. print "Displays a node. ",
  578. self._mult_id_help()
  579. def _mult_id_help(self):
  580. print "Multiple ids and nodes can be specified, separated by a space."\
  581. + "A range of ids can be specified in the format n-N. e.g. " \
  582. + "'10-20' would specify all nodes having ids from 10 to 20 " \
  583. + "inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar'" \
  584. + " would yield to all nodes with tag 'foo', node 2 and all "\
  585. + "nodes with tag 'bar'."
  586. def help_exit(self):
  587. self.usage("exit")
  588. print "Exits the application."
  589. def help_save(self):
  590. self.usage("save [filename]")
  591. print "Saves the current configuration to [filename]. If no filename "\
  592. + "is given, the configuration is saved to the file from which "\
  593. + "the initial configuration was loaded."
  594. def help_set(self):
  595. self.usage("set [configoption] [value]")
  596. print "Sets a configuration option. If no value is specified, the "\
  597. + "current value for [configoption] is output. If neither "\
  598. + "[configoption] nor [value] are specified, the whole current "\
  599. + "configuration is output. [configoption] must be of the "\
  600. + "format <section>.<option>"
  601. def help_passwd(self):
  602. self.usage("passwd")
  603. print "Changes the password on the database. "
  604. def help_forget(self):
  605. self.usage("forget")
  606. print "Forgets the database password. Your password will need to " \
  607. + "be reentered before accessing the database again."
  608. def help_clear(self):
  609. self.usage("clear")
  610. print "Clears the filter criteria. "
  611. def help_filter(self):
  612. self.usage("filter <tag> ...")
  613. print "Filters nodes on tag. Arguments can be zero or more tags. " \
  614. + "Displays current tags if called without arguments."
  615. def help_tags(self):
  616. self.usage("tags")
  617. print "Displays all tags in used in the database."
  618. def postloop(self):
  619. try:
  620. readline.write_history_file(self._historyfile)
  621. except Exception:
  622. pass
  623. def __init__(self, db, hasxsel):
  624. """
  625. initialize CLI interface, set up the DB
  626. connecion, see if we have xsel ...
  627. """
  628. _dbwarning = "\n*** WARNNING: You are using the old database format" \
  629. + " which is unsecure." \
  630. + " It's highly recommended to switch to the new database " \
  631. + "format. Do note: support for this DB format will be dropped in v0.5." \
  632. + " Check the help (pwman3 -h) or look at the manpage which" \
  633. + " explains how to proceed. ***"
  634. cmd.Cmd.__init__(self)
  635. self.intro = "%s %s (c) visit: %s %s" % (pwman.appname, pwman.version,
  636. pwman.website, _dbwarning)
  637. self._historyfile = config.get_value("Readline", "history")
  638. self.hasxsel = hasxsel
  639. try:
  640. enc = CryptoEngine.get()
  641. enc.set_callback(CLICallback())
  642. self._db = db
  643. self._db.open()
  644. except Exception, e:
  645. self.error(e)
  646. sys.exit(1)
  647. try:
  648. readline.read_history_file(self._historyfile)
  649. except IOError, e:
  650. pass
  651. self.prompt = "!pwman> "
  652. class PwmanCliNew(PwmanCli):
  653. """
  654. inherit from the old class, override
  655. all the methods related to tags, and
  656. newer Node format, so backward compatability is kept...
  657. """
  658. def __init__(self, db, hasxsel):
  659. """
  660. initialize CLI interface, set up the DB
  661. connecion, see if we have xsel ...
  662. """
  663. cmd.Cmd.__init__(self)
  664. self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version,
  665. pwman.website)
  666. self._historyfile = config.get_value("Readline", "history")
  667. self.hasxsel = hasxsel
  668. try:
  669. enc = CryptoEngine.get()
  670. #enc.set_callback(CLICallback())
  671. enc._callback = CLICallback()
  672. self._db = db
  673. self._db.open()
  674. except Exception, e:
  675. self.error(e)
  676. sys.exit(1)
  677. try:
  678. readline.read_history_file(self._historyfile)
  679. except IOError, e:
  680. pass
  681. self.prompt = "pwman> "
  682. def do_copy(self, args):
  683. if self.hasxsel:
  684. ids = self.get_ids(args)
  685. if len(ids) > 1:
  686. print "Can copy only 1 password at a time..."
  687. return None
  688. try:
  689. node = self._db.getnodes(ids)
  690. tools.text_to_clipboards(node[0].password)
  691. print "copied password for {}@{} clipboard".format(
  692. node[0].username, node[0].url)
  693. print "erasing in 10 sec..."
  694. time.sleep(10)
  695. tools.text_to_clipboards("")
  696. except Exception, e:
  697. self.error(e)
  698. else:
  699. print "Can't copy to clipboard, no xsel found in the system!"
  700. def do_open(self, args):
  701. ids = self.get_ids(args)
  702. if not args:
  703. self.help_open()
  704. return
  705. if len(ids) > 1:
  706. print "Can open only 1 link at a time ..."
  707. return None
  708. try:
  709. node = self._db.getnodes(ids)
  710. url = node[0].url
  711. tools.open_url(url)
  712. except Exception, e:
  713. self.error(e)
  714. def do_edit(self, arg):
  715. ids = self.get_ids(arg)
  716. for i in ids:
  717. try:
  718. i = int(i)
  719. node = self._db.getnodes([i])[0]
  720. menu = CliMenu()
  721. print "Editing node %d." % (i)
  722. menu.add(CliMenuItem("Username", self.get_username,
  723. node.username,
  724. node.username))
  725. menu.add(CliMenuItem("Password", self.get_password,
  726. node.password,
  727. node.password))
  728. menu.add(CliMenuItem("Url", self.get_url,
  729. node.url,
  730. node.url))
  731. menunotes = CliMenuItem("Notes", self.get_notes,
  732. node.notes,
  733. node.notes)
  734. menu.add(menunotes)
  735. menu.add(CliMenuItem("Tags", self.get_tags,
  736. node.tags,
  737. node.tags))
  738. menu.runner(node)
  739. self._db.editnode(i, node)
  740. # when done with node erase it
  741. zerome(node._password)
  742. except Exception, e:
  743. self.error(e)
  744. def print_node(self, node):
  745. width = str(tools._defaultwidth)
  746. print "Node %d." % (node._id)
  747. print ("%"+width+"s %s") % (tools.typeset("Username:", Fore.RED),
  748. node.username)
  749. print ("%"+width+"s %s") % (tools.typeset("Password:", Fore.RED),
  750. node.password)
  751. print ("%"+width+"s %s") % (tools.typeset("Url:", Fore.RED),
  752. node.url)
  753. print ("%"+width+"s %s") % (tools.typeset("Notes:", Fore.RED),
  754. node.notes)
  755. print tools.typeset("Tags: ", Fore.RED),
  756. for t in node.tags:
  757. print " %s " % t
  758. print
  759. def heardEnter():
  760. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  761. for s in i:
  762. if s == sys.stdin:
  763. sys.stdin.readline()
  764. return True
  765. return False
  766. def waituntil_enter(somepredicate, timeout, period=0.25):
  767. mustend = time.time() + timeout
  768. while time.time() < mustend:
  769. cond = somepredicate()
  770. if cond:
  771. break
  772. time.sleep(period)
  773. self.do_cls('')
  774. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  775. if flushtimeout > 0:
  776. print "Type Enter to flush screen (autoflash in "\
  777. + "%d sec.)" % flushtimeout
  778. waituntil_enter(heardEnter, flushtimeout)
  779. def do_tags(self, arg):
  780. tags = self._db.listtags()
  781. # request password
  782. enc = CryptoEngine.get()
  783. if not enc.alive():
  784. enc._getcipher()
  785. print "Tags: ",
  786. if len(tags) == 0:
  787. print "None",
  788. for t in tags:
  789. print "%s " % t,
  790. print
  791. def get_tags(self, default=None):
  792. defaultstr = ''
  793. if default:
  794. for t in default:
  795. defaultstr += "%s " % (t)
  796. else:
  797. tags = self._db.currenttags()
  798. for t in tags:
  799. defaultstr += "%s " % (t)
  800. strings = []
  801. tags = self._db.listtags(True)
  802. for t in tags:
  803. # strings.append(t.get_name())
  804. strings.append(t)
  805. def complete(text, state):
  806. count = 0
  807. for s in strings:
  808. if s.startswith(text):
  809. if count == state:
  810. return s
  811. else:
  812. count += 1
  813. taglist = tools.getinput("Tags: ", defaultstr, complete)
  814. tagstrings = taglist.split()
  815. tags = [TagN(tn) for tn in tagstrings]
  816. return tags
  817. def do_list(self, args):
  818. if len(args.split()) > 0:
  819. self.do_clear('')
  820. self.do_filter(args)
  821. try:
  822. if sys.platform != 'win32':
  823. rows, cols = tools.gettermsize()
  824. else:
  825. rows, cols = 18, 80 # fix this !
  826. nodeids = self._db.listnodes()
  827. nodes = self._db.getnodes(nodeids)
  828. cols -= 8
  829. i = 0
  830. for n in nodes:
  831. tags = n.tags
  832. tags = filter(None, tags)
  833. tagstring = ''
  834. first = True
  835. for t in tags:
  836. if not first:
  837. tagstring += ", "
  838. else:
  839. first = False
  840. tagstring += t
  841. name = "%s@%s" % (n.username, n.url)
  842. name_len = cols * 2 / 3
  843. tagstring_len = cols / 3
  844. if len(name) > name_len:
  845. name = name[:name_len-3] + "..."
  846. if len(tagstring) > tagstring_len:
  847. tagstring = tagstring[:tagstring_len-3] + "..."
  848. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  849. formatted_entry = tools.typeset(fmt % (n._id,
  850. name, tagstring),
  851. Fore.YELLOW, False)
  852. print formatted_entry
  853. i += 1
  854. if i > rows-2:
  855. i = 0
  856. c = tools.getonechar("Press <Space> for more,"
  857. " or 'Q' to cancel")
  858. if c == 'q':
  859. break
  860. except Exception, e:
  861. self.error(e)
  862. def do_filter(self, args):
  863. tagstrings = args.split()
  864. try:
  865. tags = []
  866. for ts in tagstrings:
  867. tags.append(TagN(ts))
  868. self._db.filter(tags)
  869. tags = self._db.currenttags()
  870. print "Current tags: ",
  871. if len(tags) == 0:
  872. print "None",
  873. for t in tags:
  874. print "%s " % (t.name),
  875. print
  876. except Exception, e:
  877. self.error(e)
  878. def do_new(self, args):
  879. """
  880. can override default config settings the following way:
  881. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  882. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  883. Password (Blank to generate):
  884. """
  885. errmsg = """could not parse config override, please input some"""\
  886. + """ kind of dictionary, e.g.: n {'leetify':False, """\
  887. + """'numerics':True, 'special_chars':True}"""
  888. try:
  889. username = self.get_username()
  890. if args:
  891. try:
  892. args = ast.literal_eval(args)
  893. except Exception:
  894. raise Exception(errmsg)
  895. if not isinstance(args, dict):
  896. raise Exception(errmsg)
  897. password = self.get_password(1, **args)
  898. else:
  899. numerics = config.get_value(
  900. "Generator", "numerics").lower() == 'true'
  901. # TODO: allow custom leetifying through the config
  902. leetify = config.get_value(
  903. "Generator", "leetify").lower() == 'true'
  904. special_chars = config.get_value(
  905. "Generator", "special_chars").lower() == 'true'
  906. password = self.get_password(0,
  907. numerics=numerics,
  908. symbols=leetify,
  909. special_signs=special_chars)
  910. url = self.get_url()
  911. notes = self.get_notes()
  912. node = NewNode(username, password, url, notes)
  913. node.tags = self.get_tags()
  914. self._db.addnodes([node])
  915. print "Password ID: %d" % (node._id)
  916. # when done with node erase it
  917. zerome(password)
  918. except Exception, e:
  919. self.error(e)
  920. def do_print(self, arg):
  921. for i in self.get_ids(arg):
  922. try:
  923. node = self._db.getnodes([i])
  924. self.print_node(node[0])
  925. # when done with node erase it
  926. zerome(node[0]._password)
  927. except Exception, e:
  928. self.error(e)
  929. def do_delete(self, arg):
  930. ids = self.get_ids(arg)
  931. try:
  932. nodes = self._db.getnodes(ids)
  933. for n in nodes:
  934. b = tools.getyesno("Are you sure you want to delete '%s@%s'?"
  935. % (n.username, n.url), False)
  936. if b is True:
  937. self._db.removenodes([n])
  938. print "%s@%s deleted" % (n.username, n.url)
  939. except Exception, e:
  940. self.error(e)