base.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  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) 2013 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. # pylint: disable=I0011
  20. """
  21. Define the base CLI interface for pwman3
  22. """
  23. from __future__ import print_function
  24. class HelpUI(object):
  25. """
  26. this class holds all the UI help functionality.
  27. in PwmanCliNew. The later inherits from this class
  28. and allows it to print help messages to the console.
  29. """
  30. def usage(self, string):
  31. print ("Usage: %s" % (string))
  32. def help_open(self):
  33. self.usage("open <ID>")
  34. print ("Launch default browser with 'xdg-open url',\n",
  35. "the url must contain http:// or https://.")
  36. def help_o(self):
  37. self.help_open()
  38. def help_copy(self):
  39. self.usage("copy <ID>")
  40. print ("Copy password to X clipboard (xsel required)")
  41. def help_cp(self):
  42. self.help_copy()
  43. def help_cls(self):
  44. self.usage("cls")
  45. print ("Clear the Screen from information.")
  46. def help_list(self):
  47. self.usage("list <tag> ...")
  48. print ("List nodes that match current or specified filter.",
  49. " l is an alias.")
  50. def help_EOF(self):
  51. self.help_exit()
  52. def help_delete(self):
  53. self.usage("delete <ID|tag> ...")
  54. print ("Deletes nodes. rm is an alias.")
  55. self._mult_id_help()
  56. def help_h(self):
  57. self.help_help()
  58. def help_help(self):
  59. self.usage("help [topic]")
  60. print ("Prints a help message for a command.")
  61. def help_e(self):
  62. self.help_edit()
  63. def help_n(self):
  64. self.help_new()
  65. def help_p(self):
  66. self.help_print()
  67. def help_l(self):
  68. self.help_list()
  69. def help_edit(self):
  70. self.usage("edit <ID|tag> ... ")
  71. print ("Edits a nodes.")
  72. self._mult_id_help()
  73. def help_import(self):
  74. self.usage("import [filename] ...")
  75. print ("Imports a nodes from a file.")
  76. def help_export(self):
  77. self.usage("export <ID|tag> ... ")
  78. print ("Exports a list of ids to an external format. If no IDs or",
  79. " tags are specified, then all nodes under the current",
  80. " filter are exported.")
  81. self._mult_id_help()
  82. def help_new(self):
  83. self.usage("new")
  84. print ("Creates a new node.,",
  85. "You can override default config settings the following way:\n",
  86. "pwman> n {'leetify':False, 'numerics':True}")
  87. def help_rm(self):
  88. self.help_delete()
  89. def help_print(self):
  90. self.usage("print <ID|tag> ...")
  91. print ("Displays a node. ")
  92. self._mult_id_help()
  93. def _mult_id_help(self):
  94. print("Multiple ids and nodes can be specified, separated by a space.",
  95. " A range of ids can be specified in the format n-N. e.g. ",
  96. " '10-20' would specify all nodes having ids from 10 to 20 ",
  97. " inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar'",
  98. " would yield to all nodes with tag 'foo', node 2 and all ",
  99. " nodes with tag 'bar'.")
  100. def help_exit(self):
  101. self.usage("exit")
  102. print("Exits the application.")
  103. def help_save(self):
  104. self.usage("save [filename]")
  105. print("Saves the current configuration to [filename]. If no filename ",
  106. "is given, the configuration is saved to the file from which ",
  107. "the initial configuration was loaded.")
  108. def help_set(self):
  109. self.usage("set [configoption] [value]")
  110. print("Sets a configuration option. If no value is specified, the ",
  111. "current value for [configoption] is output. If neither ",
  112. "[configoption] nor [value] are specified, the whole current ",
  113. "configuration is output. [configoption] must be of the ",
  114. "format <section>.<option>")
  115. def help_passwd(self):
  116. self.usage("passwd")
  117. print("Changes the password on the database. ")
  118. def help_forget(self):
  119. self.usage("forget")
  120. print("Forgets the database password. Your password will need to ",
  121. "be reentered before accessing the database again.")
  122. def help_clear(self):
  123. self.usage("clear")
  124. print("Clears the filter criteria. ")
  125. def help_filter(self):
  126. self.usage("filter <tag> ...")
  127. print("Filters nodes on tag. Arguments can be zero or more tags. ",
  128. "Displays current tags if called without arguments.")
  129. def help_tags(self):
  130. self.usage("tags")
  131. print("Displays all tags in used in the database.")
  132. class BaseUI(object):
  133. """
  134. this class holds all the UI functionality
  135. in PwmanCliNew. The later inherits from this class
  136. and allows it to print messages to the console.
  137. """
  138. def _do_filter(self, args):
  139. pass
  140. def _tags(self, enc):
  141. """
  142. read tags from TAGS table in DB,
  143. this method has a working unittest
  144. """
  145. tags = self._db.listtags()
  146. if tags:
  147. _tags = [''] * len(tags)
  148. for t in tags:
  149. try:
  150. _tags.append(enc.decrypt(t))
  151. except (ValueError, Exception), e:
  152. _tags.append(t)
  153. del(e)
  154. _tags = filter(None, _tags)
  155. return _tags
  156. import pwman.exchange.importer as importer
  157. from pwman.util.crypto import CryptoEngine
  158. from pwman.util.crypto import zerome
  159. import pwman.util.config as config
  160. import re
  161. import sys
  162. import os
  163. import time
  164. import select as uselect
  165. import ast
  166. from pwman.ui import tools
  167. from pwman.ui.tools import CliMenu
  168. from pwman.ui.tools import CliMenuItem
  169. from colorama import Fore
  170. from pwman.data.nodes import NewNode
  171. from pwman.ui.tools import CMDLoop
  172. import getpass
  173. from pwman.data.tags import TagNew
  174. def get_pass_conf():
  175. numerics = config.get_value("Generator", "numerics").lower() == 'true'
  176. # TODO: allow custom leetifying through the config
  177. leetify = config.get_value("Generator", "leetify").lower() == 'true'
  178. special_chars = config.get_value("Generator", "special_chars"
  179. ).lower() == 'true'
  180. return numerics, leetify, special_chars
  181. # pylint: disable=R0904
  182. class PwmanCliOld(HelpUI, BaseUI):
  183. def do_exit(self, args):
  184. """exit the ui"""
  185. self._db.close()
  186. return True
  187. def do_edit(self, arg):
  188. ids = self.get_ids(arg)
  189. for i in ids:
  190. try:
  191. i = int(i)
  192. node = self._db.getnodes([i])[0]
  193. menu = CliMenu()
  194. print ("Editing node %d." % (i))
  195. menu.add(CliMenuItem("Username", self.get_username,
  196. node.get_username,
  197. node.set_username))
  198. menu.add(CliMenuItem("Password", self.get_password,
  199. node.get_password,
  200. node.set_password))
  201. menu.add(CliMenuItem("Url", self.get_url,
  202. node.get_url,
  203. node.set_url))
  204. menu.add(CliMenuItem("Notes", self.get_notes,
  205. node.get_notes,
  206. node.set_notes))
  207. menu.add(CliMenuItem("Tags", self.get_tags,
  208. node.get_tags,
  209. node.set_tags))
  210. menu.run()
  211. self._db.editnode(i, node)
  212. # when done with node erase it
  213. zerome(node._password)
  214. except Exception, e:
  215. self.error(e)
  216. def do_import(self, arg):
  217. try:
  218. args = arg.split()
  219. if len(args) == 0:
  220. types = importer.Importer.types()
  221. intype = tools.select("Select filetype:", types)
  222. imp = importer.Importer.get(intype)
  223. infile = tools.getinput("Select file:")
  224. imp.import_data(self._db, infile)
  225. else:
  226. for i in args:
  227. types = importer.Importer.types()
  228. intype = tools.select("Select filetype:", types)
  229. imp = importer.Importer.get(intype)
  230. imp.import_data(self._db, i)
  231. except Exception, e:
  232. self.error(e)
  233. def do_export(self, arg):
  234. print('Not implemented...')
  235. def do_delete(self, arg):
  236. ids = self.get_ids(arg)
  237. try:
  238. nodes = self._db.getnodes(ids)
  239. for n in nodes:
  240. b = tools.getyesno("Are you sure you want to delete '%s@%s'?"
  241. % (n.get_username(), n.get_url()), False)
  242. if b is True:
  243. self._db.removenodes([n])
  244. print ("%s@%s deleted" % (n.get_username(), n.get_url()))
  245. except Exception, e:
  246. self.error(e)
  247. def do_list(self, args):
  248. """
  249. TODO: in order to make this code testable
  250. The functionality in this method should
  251. go to a method that returns a string.
  252. This method should only do the printing.
  253. """
  254. if len(args.split()) > 0:
  255. self.do_clear('')
  256. self.do_filter(args)
  257. try:
  258. if sys.platform != 'win32':
  259. rows, cols = tools.gettermsize()
  260. else:
  261. rows, cols = 18, 80
  262. nodeids = self._db.listnodes()
  263. nodes = self._db.getnodes(nodeids)
  264. cols -= 8
  265. i = 0
  266. for n in nodes:
  267. tags = n.get_tags()
  268. tagstring = ''
  269. first = True
  270. for t in tags:
  271. if not first:
  272. tagstring += ", "
  273. else:
  274. first = False
  275. tagstring += t.get_name()
  276. name = "%s@%s" % (n.get_username(), n.get_url())
  277. name_len = cols * 2 / 3
  278. tagstring_len = cols / 3
  279. if len(name) > name_len:
  280. name = name[:name_len - 3] + "..."
  281. if len(tagstring) > tagstring_len:
  282. tagstring = tagstring[:tagstring_len - 3] + "..."
  283. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  284. print (tools.typeset(fmt % (n.get_id(), name, tagstring),
  285. Fore.YELLOW, False))
  286. i += 1
  287. if i > rows - 2:
  288. i = 0
  289. c = tools.getonechar("Press <Space> for more, "
  290. "or 'Q' to cancel")
  291. if c == 'q':
  292. break
  293. except Exception, e:
  294. self.error(e)
  295. def do_forget(self, args):
  296. try:
  297. enc = CryptoEngine.get()
  298. enc.forget()
  299. except Exception, e:
  300. self.error(e)
  301. def do_open(self, args):
  302. ids = self.get_ids(args)
  303. if not args:
  304. self.help_open()
  305. return
  306. if len(ids) > 1:
  307. print ("Can open only 1 link at a time ...")
  308. return None
  309. try:
  310. node = self._db.getnodes(ids)
  311. url = node[0].get_url()
  312. tools.open_url(url)
  313. except Exception, e:
  314. self.error(e)
  315. def __init__(self, db, hasxsel):
  316. """
  317. initialize CLI interface, set up the DB
  318. connecion, see if we have xsel ...
  319. """
  320. _dbwarning = "\n*** WARNNING: You are using the old database format" \
  321. + " which is unsecure." \
  322. + " This database format is in hold. No bugs are fixed. Please " \
  323. + " upgrade your database." \
  324. + " Check the help (pwman3 -h) or look at the manpage which" \
  325. + " explains how to proceed. ***"
  326. print (_dbwarning)
  327. sys.exit(1)
  328. class BaseCommands(PwmanCliOld):
  329. """
  330. Inherit from the old class, override
  331. all the methods related to tags, and
  332. newer Node format, so backward compatability is kept...
  333. Commands defined here, can have aliases definded in Aliases.
  334. You can define the aliases here too, but it makes
  335. the class code really long and unclear.
  336. """
  337. def error(self, exception):
  338. if (isinstance(exception, KeyboardInterrupt)):
  339. print('')
  340. else:
  341. print("Error: {0} ".format(exception))
  342. def do_copy(self, args):
  343. if self.hasxsel:
  344. ids = self.get_ids(args)
  345. if len(ids) > 1:
  346. print ("Can copy only 1 password at a time...")
  347. return None
  348. try:
  349. node = self._db.getnodes(ids)
  350. tools.text_to_clipboards(node[0].password)
  351. print ("copied password for {}@{} clipboard".format(
  352. node[0].username, node[0].url))
  353. print ("erasing in 10 sec...")
  354. time.sleep(10)
  355. tools.text_to_clipboards("")
  356. except Exception, e:
  357. self.error(e)
  358. else:
  359. print ("Can't copy to clipboard, no xsel found in the system!")
  360. def do_set(self, args):
  361. argstrs = args.split()
  362. try:
  363. if len(argstrs) == 0:
  364. conf = config.get_conf()
  365. for s in conf.keys():
  366. for n in conf[s].keys():
  367. print ("%s.%s = %s" % (s, n, conf[s][n]))
  368. elif len(argstrs) == 1:
  369. r = re.compile("(.+)\.(.+)")
  370. m = r.match(argstrs[0])
  371. if m is None or len(m.groups()) != 2:
  372. print ("Invalid option format")
  373. self.help_set()
  374. return
  375. print ("%s.%s = %s" % (m.group(1), m.group(2),
  376. config.get_value(m.group(1),
  377. m.group(2))))
  378. elif len(argstrs) == 2:
  379. r = re.compile("(.+)\.(.+)")
  380. m = r.match(argstrs[0])
  381. if m is None or len(m.groups()) != 2:
  382. print ("Invalid option format")
  383. self.help_set()
  384. return
  385. config.set_value(m.group(1), m.group(2), argstrs[1])
  386. else:
  387. self.help_set()
  388. except Exception, e:
  389. self.error(e)
  390. def get_username(self, default="", reader=raw_input):
  391. return tools.getinput("Username: ", default, reader)
  392. def get_url(self, default="", reader=raw_input):
  393. return tools.getinput("Url: ", default, reader)
  394. def get_notes(self, default="", reader=raw_input):
  395. return tools.getinput("Notes: ", default, reader)
  396. def do_open(self, args):
  397. ids = self.get_ids(args)
  398. if not args:
  399. self.help_open()
  400. return
  401. if len(ids) > 1:
  402. print ("Can open only 1 link at a time ...")
  403. return None
  404. try:
  405. node = self._db.getnodes(ids)
  406. url = node[0].url
  407. tools.open_url(url)
  408. except Exception, e:
  409. self.error(e)
  410. def do_clear(self, args):
  411. try:
  412. self._db.clearfilter()
  413. except Exception, e:
  414. self.error(e)
  415. def do_cls(self, args):
  416. os.system('clear')
  417. def do_edit(self, arg, menu=None):
  418. ids = self.get_ids(arg)
  419. for i in ids:
  420. try:
  421. i = int(i)
  422. node = self._db.getnodes([i])[0]
  423. if not menu:
  424. menu = CMDLoop()
  425. print ("Editing node %d." % (i))
  426. menu.add(CliMenuItem("Username", self.get_username,
  427. node.username,
  428. node.username))
  429. menu.add(CliMenuItem("Password", self.get_password,
  430. node.password,
  431. node.password))
  432. menu.add(CliMenuItem("Url", self.get_url,
  433. node.url,
  434. node.url))
  435. menunotes = CliMenuItem("Notes", self.get_notes,
  436. node.notes,
  437. node.notes)
  438. menu.add(menunotes)
  439. menu.add(CliMenuItem("Tags", self.get_tags,
  440. node.tags,
  441. node.tags))
  442. menu.run(node)
  443. self._db.editnode(i, node)
  444. # when done with node erase it
  445. zerome(node._password)
  446. except Exception, e:
  447. self.error(e)
  448. def print_node(self, node):
  449. width = str(tools._defaultwidth)
  450. print ("Node %d." % (node._id))
  451. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  452. node.username))
  453. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  454. node.password))
  455. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  456. node.url))
  457. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  458. node.notes))
  459. print (tools.typeset("Tags: ", Fore.RED)),
  460. for t in node.tags:
  461. print (" %s " % t)
  462. print()
  463. def heardEnter():
  464. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  465. for s in i:
  466. if s == sys.stdin:
  467. sys.stdin.readline()
  468. return True
  469. return False
  470. def waituntil_enter(somepredicate, timeout, period=0.25):
  471. mustend = time.time() + timeout
  472. while time.time() < mustend:
  473. cond = somepredicate()
  474. if cond:
  475. break
  476. time.sleep(period)
  477. self.do_cls('')
  478. try:
  479. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  480. except ValueError:
  481. flushtimeout = 10
  482. if flushtimeout > 0:
  483. print ("Type Enter to flush screen (autoflash in "
  484. "%d sec.)" % flushtimeout)
  485. waituntil_enter(heardEnter, flushtimeout)
  486. def do_passwd(self, args):
  487. try:
  488. key = self._db.changepassword()
  489. self._db._save(key)
  490. except Exception, e:
  491. self.error(e)
  492. def do_save(self, args):
  493. argstrs = args.split()
  494. try:
  495. if len(argstrs) > 0:
  496. config.save(argstrs[0])
  497. else:
  498. config.save()
  499. print ("Config saved.")
  500. except Exception, e:
  501. self.error(e)
  502. def do_tags(self, arg):
  503. enc = CryptoEngine.get()
  504. if not enc.alive():
  505. enc._getcipher()
  506. print ("Tags: \n",)
  507. t = self._tags(enc)
  508. print ('\n'.join(t))
  509. def get_tags(self, default=None, reader=raw_input):
  510. """read tags from user"""
  511. defaultstr = ''
  512. if default:
  513. for t in default:
  514. defaultstr += "%s " % (t)
  515. else:
  516. # tags = self._db.currenttags()
  517. tags = self._db._filtertags
  518. for t in tags:
  519. defaultstr += "%s " % (t)
  520. # strings = []
  521. tags = self._db.listtags(True)
  522. # for t in tags:
  523. # strings.append(t.get_name())
  524. # strings.append(t)
  525. strings = [t for t in tags]
  526. def complete(text, state):
  527. count = 0
  528. for s in strings:
  529. if s.startswith(text):
  530. if count == state:
  531. return s
  532. else:
  533. count += 1
  534. taglist = tools.getinput("Tags: ", defaultstr, completer=complete,
  535. reader=reader)
  536. tagstrings = taglist.split()
  537. tags = [TagNew(tn) for tn in tagstrings]
  538. return tags
  539. def do_list(self, args):
  540. if len(args.split()) > 0:
  541. self.do_clear('')
  542. self.do_filter(args)
  543. try:
  544. if sys.platform != 'win32':
  545. rows, cols = tools.gettermsize()
  546. else:
  547. rows, cols = 18, 80 # fix this !
  548. nodeids = self._db.listnodes()
  549. nodes = self._db.getnodes(nodeids)
  550. cols -= 8
  551. i = 0
  552. for n in nodes:
  553. tags = n.tags
  554. tags = filter(None, tags)
  555. tagstring = ''
  556. first = True
  557. for t in tags:
  558. if not first:
  559. tagstring += ", "
  560. else:
  561. first = False
  562. tagstring += t
  563. name = "%s@%s" % (n.username, n.url)
  564. name_len = cols * 2 / 3
  565. tagstring_len = cols / 3
  566. if len(name) > name_len:
  567. name = name[:name_len - 3] + "..."
  568. if len(tagstring) > tagstring_len:
  569. tagstring = tagstring[:tagstring_len - 3] + "..."
  570. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  571. formatted_entry = tools.typeset(fmt % (n._id,
  572. name, tagstring),
  573. Fore.YELLOW, False)
  574. print (formatted_entry)
  575. i += 1
  576. if i > rows - 2:
  577. i = 0
  578. c = tools.getonechar("Press <Space> for more,"
  579. " or 'Q' to cancel")
  580. if c.lower() == 'q':
  581. break
  582. except Exception, e:
  583. self.error(e)
  584. def do_filter(self, args):
  585. tagstrings = args.split()
  586. try:
  587. tags = [TagNew(ts) for ts in tagstrings]
  588. self._db.filter(tags)
  589. tags = self._db.currenttags()
  590. print ("Current tags: ",)
  591. if len(tags) == 0:
  592. print ("None",)
  593. for t in tags:
  594. print ("%s " % t)
  595. print
  596. except Exception, e:
  597. self.error(e)
  598. def do_new(self, args):
  599. """
  600. can override default config settings the following way:
  601. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  602. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  603. Password (Blank to generate):
  604. """
  605. errmsg = ("could not parse config override, please input some"
  606. " kind of dictionary, e.g.: n {'leetify':False, "
  607. " numerics':True, 'special_chars':True}")
  608. try:
  609. username = self.get_username()
  610. if args:
  611. try:
  612. args = ast.literal_eval(args)
  613. except Exception:
  614. raise Exception(errmsg)
  615. if not isinstance(args, dict):
  616. raise Exception(errmsg)
  617. password = self.get_password(argsgiven=1, **args)
  618. else:
  619. numerics, leet, s_chars = get_pass_conf()
  620. password = self.get_password(argsgiven=0,
  621. numerics=numerics,
  622. symbols=leet,
  623. special_signs=s_chars)
  624. url = self.get_url()
  625. notes = self.get_notes()
  626. node = NewNode()
  627. node.username = username
  628. node.password = password
  629. node.url = url
  630. node.notes = notes
  631. #node = NewNode(username, password, url, notes)
  632. node.tags = self.get_tags()
  633. self._db.addnodes([node])
  634. print ("Password ID: %d" % (node._id))
  635. # when done with node erase it
  636. zerome(password)
  637. except Exception, e:
  638. self.error(e)
  639. def do_print(self, arg):
  640. for i in self.get_ids(arg):
  641. try:
  642. node = self._db.getnodes([i])
  643. self.print_node(node[0])
  644. # when done with node erase it
  645. zerome(node[0]._password)
  646. except Exception, e:
  647. self.error(e)
  648. def do_delete(self, arg):
  649. ids = self.get_ids(arg)
  650. try:
  651. nodes = self._db.getnodes(ids)
  652. for n in nodes:
  653. try:
  654. b = tools.getyesno(("Are you sure you want to"
  655. " delete '%s@%s'?"
  656. ) % (n.username, n.url), False)
  657. except NameError:
  658. pass
  659. if b is True:
  660. self._db.removenodes([n])
  661. print ("%s@%s deleted" % (n.username, n.url))
  662. except Exception, e:
  663. self.error(e)
  664. def get_ids(self, args):
  665. """
  666. Command can get a single ID or
  667. a range of IDs, with begin-end.
  668. e.g. 1-3 , will get 1 to 3.
  669. """
  670. ids = []
  671. rex = re.compile("^(?P<begin>\d+)(?:-(?P<end>\d+))?$")
  672. rex = rex.match(args)
  673. if hasattr(rex, 'groupdict'):
  674. try:
  675. begin = int(rex.groupdict()['begin'])
  676. end = int(rex.groupdict()['end'])
  677. if not end > begin:
  678. print("Start node should be smaller than end node")
  679. return ids
  680. ids += range(begin, end+1)
  681. return ids
  682. except TypeError:
  683. ids.append(int(begin))
  684. else:
  685. print("Could not understand your input...")
  686. return ids
  687. def get_password(self, argsgiven, numerics=False, leetify=False,
  688. symbols=False, special_signs=False,
  689. reader=getpass.getpass, length=None):
  690. return tools.getpassword("Password (Blank to generate): ",
  691. reader=reader, length=length, leetify=leetify)
  692. class Aliases(BaseCommands, PwmanCliOld):
  693. """
  694. Define all the alias you want here...
  695. """
  696. def do_cp(self, args):
  697. self.do_copy(args)
  698. def do_e(self, arg):
  699. self.do_edit(arg)
  700. def do_EOF(self, args):
  701. return self.do_exit(args)
  702. def do_l(self, args):
  703. self.do_list(args)
  704. def do_ls(self, args):
  705. self.do_list(args)
  706. def do_p(self, arg):
  707. self.do_print(arg)
  708. def do_rm(self, arg):
  709. self.do_delete(arg)
  710. def do_o(self, args):
  711. self.do_open(args)
  712. def do_h(self, arg):
  713. self.do_help(arg)
  714. def do_n(self, arg):
  715. self.do_new(arg)