cli.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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) 2006 Ivan Kelly <ivan@ivankelly.net>
  18. #============================================================================
  19. import pwman
  20. import pwman.exchange.importer as importer
  21. import pwman.exchange.exporter as exporter
  22. import pwman.util.generator as generator
  23. from pwman.data.nodes import Node
  24. from pwman.data.tags import Tag
  25. from pwman.util.crypto import CryptoEngine, CryptoBadKeyException, \
  26. CryptoPasswordMismatchException
  27. from pwman.util.callback import Callback
  28. import pwman.util.config as config
  29. import re
  30. import sys
  31. import tty
  32. import os
  33. import getpass
  34. import cmd
  35. import traceback
  36. try:
  37. import readline
  38. _readline_available = True
  39. except ImportError, e:
  40. _readline_available = False
  41. class CLICallback(Callback):
  42. def getinput(self, question):
  43. return raw_input(question)
  44. def getsecret(self, question):
  45. return getpass.getpass(question + ":")
  46. class ANSI(object):
  47. Reset = 0
  48. Bold = 1
  49. Underscore = 2
  50. Black = 30
  51. Red = 31
  52. Green = 32
  53. Yellow = 33
  54. Blue = 34
  55. Magenta = 35
  56. Cyan = 36
  57. White = 37
  58. class PwmanCli(cmd.Cmd):
  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. print
  69. try:
  70. self._db.close()
  71. except Exception, e:
  72. self.error(e)
  73. return True
  74. def get_ids(self, args):
  75. ids = []
  76. rx =re.compile(r"^(\d+)-(\d+)$")
  77. idstrs = args.split()
  78. for i in idstrs:
  79. m = rx.match(i)
  80. if m == None:
  81. ids.append(int(i))
  82. else:
  83. ids += range(int(m.group(1)),
  84. int(m.group(2))+1)
  85. return ids
  86. def get_filesystem_path(self, default=""):
  87. return getinput("Enter filename: ", default)
  88. def get_username(self, default=""):
  89. return getinput("Username: ", default)
  90. def get_password(self, default=""):
  91. password = getpassword("Password (Blank to generate): ", _defaultwidth, False)
  92. if len(password) == 0:
  93. length = getinput("Password length (default 7): ", "7")
  94. length = int(length)
  95. (password, dumpme) = generator.generate_password(length, length)
  96. print "New password: %s" % (password)
  97. return password
  98. else:
  99. return password
  100. def get_url(self, default=""):
  101. return getinput("Url: ", default)
  102. def get_notes(self, default=""):
  103. return getinput("Notes: ", default)
  104. def get_tags(self, default=[]):
  105. defaultstr = ''
  106. if len(default) > 0:
  107. for t in default:
  108. defaultstr += "%s " % (t.get_name())
  109. else:
  110. tags = self._db.currenttags()
  111. for t in tags:
  112. defaultstr += "%s " % (t.get_name())
  113. strings = []
  114. tags = self._db.listtags(True)
  115. for t in tags:
  116. strings.append(t.get_name())
  117. def complete(text, state):
  118. count = 0
  119. for s in strings:
  120. if s.startswith(text):
  121. if count == state:
  122. return s
  123. else:
  124. count += 1
  125. taglist = getinput("Tags: ", defaultstr, complete)
  126. tagstrings = taglist.split()
  127. tags = []
  128. for tn in tagstrings:
  129. tags.append(Tag(tn))
  130. return tags
  131. def print_node(self, node):
  132. width = str(_defaultwidth)
  133. print "Node %d." % (node.get_id())
  134. print ("%"+width+"s %s") % (typeset("Username:", ANSI.Red),
  135. node.get_username())
  136. print ("%"+width+"s %s") % (typeset("Password:", ANSI.Red),
  137. node.get_password())
  138. print ("%"+width+"s %s") % (typeset("Url:", ANSI.Red),
  139. node.get_url())
  140. print ("%"+width+"s %s") % (typeset("Notes:", ANSI.Red),
  141. node.get_notes())
  142. print typeset("Tags: ", ANSI.Red),
  143. for t in node.get_tags():
  144. print "%s " % t.get_name(),
  145. print
  146. def do_tags(self, arg):
  147. tags = self._db.listtags()
  148. if len(tags) > 0:
  149. tags[0].get_name() # hack to get password request before output
  150. print "Tags: ",
  151. if len(tags) == 0:
  152. print "None",
  153. for t in tags:
  154. print "%s " % (t.get_name()),
  155. print
  156. def complete_filter(self, text, line, begidx, endidx):
  157. strings = []
  158. enc = CryptoEngine.get()
  159. if not enc.alive():
  160. return strings
  161. tags = self._db.listtags()
  162. for t in tags:
  163. name = t.get_name()
  164. if name.startswith(text):
  165. strings.append(t.get_name())
  166. return strings
  167. def do_filter(self, args):
  168. tagstrings = args.split()
  169. try:
  170. tags = []
  171. for ts in tagstrings:
  172. tags.append(Tag(ts))
  173. self._db.filter(tags)
  174. tags = self._db.currenttags()
  175. print "Current tags: ",
  176. if len(tags) == 0:
  177. print "None",
  178. for t in tags:
  179. print "%s " % (t.get_name()),
  180. print
  181. except Exception, e:
  182. self.error(e)
  183. def do_clear(self, args):
  184. try:
  185. self._db.clearfilter()
  186. except Exception, e:
  187. self.error(e)
  188. def do_e(self, arg):
  189. self.do_edit(arg)
  190. def do_edit(self, arg):
  191. ids = self.get_ids(arg)
  192. for i in ids:
  193. try:
  194. i = int(i)
  195. node = self._db.getnodes([i])[0]
  196. menu = CliMenu()
  197. print "Editing node %d." % (i)
  198. menu.add(CliMenuItem("Username", self.get_username,
  199. node.get_username,
  200. node.set_username))
  201. menu.add(CliMenuItem("Password", self.get_password,
  202. node.get_password,
  203. node.set_password))
  204. menu.add(CliMenuItem("Url", self.get_url,
  205. node.get_url,
  206. node.set_url))
  207. menu.add(CliMenuItem("Notes", self.get_notes,
  208. node.get_notes,
  209. node.set_notes))
  210. menu.add(CliMenuItem("Tags", self.get_tags,
  211. node.get_tags,
  212. node.set_tags))
  213. menu.run()
  214. self._db.editnode(i, node)
  215. except Exception, e:
  216. self.error(e)
  217. def do_import(self, arg):
  218. try:
  219. args = arg.split()
  220. if len(args) == 0:
  221. types = importer.Importer.types()
  222. type = select("Select filetype:", types)
  223. imp = importer.Importer.get(type)
  224. file = getinput("Select file:")
  225. imp.import_data(self._db, file)
  226. else:
  227. for i in args:
  228. types = importer.Importer.types()
  229. type = select("Select filetype:", types)
  230. imp = importer.Importer.get(type)
  231. imp.import_data(self._db, i)
  232. except Exception, e:
  233. self.error(e)
  234. def do_export(self, arg):
  235. try:
  236. nodes = self.get_ids(arg)
  237. types = exporter.Exporter.types()
  238. type = select("Select filetype:", types)
  239. exp = exporter.Exporter.get(type)
  240. file = getinput("Select output file:")
  241. if len(nodes) > 0:
  242. b = getyesno("Export nodes %s?" % (nodes), True)
  243. if not b:
  244. return
  245. exp.export_data(self._db, file, nodes)
  246. else:
  247. nodes = self._db.listnodes()
  248. tags = self._db.currenttags()
  249. tagstr = ""
  250. if len(tags) > 0:
  251. tagstr = " for "
  252. for t in tags:
  253. tagstr += "'%s' " % (t.get_name())
  254. b = getyesno("Export all nodes%s?" % (tagstr), True)
  255. if not b:
  256. return
  257. exp.export_data(self._db, file, nodes)
  258. print "Data exported."
  259. except Exception, e:
  260. self.error(e)
  261. def do_h(self, arg):
  262. self.do_help(arg)
  263. def do_n(self, arg):
  264. self.do_new(arg)
  265. def do_new(self, arg):
  266. try:
  267. username = self.get_username()
  268. password = self.get_password()
  269. url = self.get_url()
  270. notes = self.get_notes()
  271. node = Node(username, password, url, notes)
  272. tags = self.get_tags()
  273. node.set_tags(tags)
  274. self._db.addnodes([node])
  275. print "Password ID: %d" % (node.get_id())
  276. except Exception, e:
  277. self.error(e)
  278. def do_p(self, arg):
  279. self.do_print(arg)
  280. def do_print(self, arg):
  281. for i in self.get_ids(arg):
  282. try:
  283. node = self._db.getnodes([i])
  284. self.print_node(node[0])
  285. except Exception, e:
  286. self.error(e)
  287. def do_rm(self, arg):
  288. self.do_delete(arg)
  289. def do_delete(self, arg):
  290. ids = self.get_ids(arg)
  291. try:
  292. nodes = self._db.getnodes(ids)
  293. for n in nodes:
  294. b = getyesno("Are you sure you want to delete '%s@%s'?"
  295. % (n.get_username(), n.get_url()), False)
  296. if b == True:
  297. self._db.removenodes([n])
  298. print "%s@%s deleted" % (n.get_username(), n.get_url())
  299. except Exception, e:
  300. self.error(e)
  301. def do_l(self, args):
  302. self.do_list(args)
  303. def do_ls(self, args):
  304. self.do_list(args)
  305. def do_list(self, args):
  306. self.do_filter('')
  307. try:
  308. nodeids = self._db.listnodes()
  309. nodes = self._db.getnodes(nodeids)
  310. i = 0
  311. for n in nodes:
  312. tags=n.get_tags()
  313. tagstring = ''
  314. first = True
  315. for t in tags:
  316. if not first:
  317. tagstring += ", "
  318. else:
  319. first=False
  320. tagstring += t.get_name()
  321. name = "%s@%s" % (n.get_username(), n.get_url())
  322. if len(name) > 30:
  323. name = name[:27] + "..."
  324. if len(tagstring) > 20:
  325. tagstring = tagstring[:17] + "..."
  326. print typeset("%5d. %-30s %-20s" % (n.get_id(), name, tagstring),
  327. ANSI.Yellow, False)
  328. i += 1
  329. if i > 23:
  330. i = 0
  331. c = getonechar("Press <Space> for more, or 'Q' to cancel")
  332. if c == 'q':
  333. break
  334. except Exception, e:
  335. self.error(e)
  336. def do_forget(self, args):
  337. try:
  338. enc = CryptoEngine.get()
  339. enc.forget()
  340. except Exception,e:
  341. self.error(e)
  342. def do_passwd(self, args):
  343. try:
  344. self._db.changepassword()
  345. except Exception, e:
  346. self.error(e)
  347. def do_set(self, args):
  348. argstrs = args.split()
  349. try:
  350. if len(argstrs) == 0:
  351. conf = config.get_conf()
  352. for s in conf.keys():
  353. for n in conf[s].keys():
  354. print "%s.%s = %s" % (s, n, conf[s][n])
  355. elif len(argstrs) == 1:
  356. r = re.compile("(.+)\.(.+)")
  357. m = r.match(argstrs[0])
  358. if m is None or len(m.groups()) != 2:
  359. print "Invalid option format"
  360. self.help_set()
  361. return
  362. print "%s.%s = %s" % (m.group(1), m.group(2),
  363. config.get_value(m.group(1), m.group(2)))
  364. elif len(argstrs) == 2:
  365. r = re.compile("(.+)\.(.+)")
  366. m = r.match(argstrs[0])
  367. if m is None or len(m.groups()) != 2:
  368. print "Invalid option format"
  369. self.help_set()
  370. return
  371. config.set_value(m.group(1), m.group(2), argstrs[1])
  372. else:
  373. self.help_set()
  374. except Exception, e:
  375. self.error(e)
  376. def do_save(self, args):
  377. argstrs = args.split()
  378. try:
  379. if len(argstrs) > 0:
  380. config.save(argstrs[0])
  381. else:
  382. config.save()
  383. print "Config saved."
  384. except Exception, e:
  385. self.error(e)
  386. ##
  387. ## Help functions
  388. ##
  389. def usage(self, string):
  390. print "Usage: %s" % (string)
  391. def help_ls(self):
  392. self.help_list()
  393. def help_list(self):
  394. self.usage("list")
  395. print "List nodes that match current filter. ls is an alias."
  396. def help_EOF(self):
  397. self.help_exit()
  398. def help_delete(self):
  399. self.usage("delete <ID> ...")
  400. print "Deletes nodes. rm is an alias."
  401. self._mult_id_help()
  402. def help_h(self):
  403. self.help_help()
  404. def help_help(self):
  405. self.usage("help [topic]")
  406. print "Prints a help message for a command."
  407. def help_e(self):
  408. self.help_edit()
  409. def help_n(self):
  410. self.help_new()
  411. def help_p(self):
  412. self.help_print()
  413. def help_l(self):
  414. self.help_list()
  415. def help_edit(self):
  416. self.usage("edit <ID> ... ")
  417. print "Edits a nodes."
  418. self._mult_id_help()
  419. def help_import(self):
  420. self.usage("import [filename] ...")
  421. print "Imports a nodes from a file."
  422. def help_export(self):
  423. self.usage("export <ID> ... ")
  424. print "Exports a list of ids to an external format. If no IDs are specified, then all nodes under the current filter are exported."
  425. self._mult_id_help()
  426. def help_new(self):
  427. self.usage("new")
  428. print "Creates a new node."
  429. def help_rm(self):
  430. self.help_delete()
  431. def help_print(self):
  432. self.usage("print <ID> ...")
  433. print "Displays a node. ",
  434. self._mult_id_help()
  435. def _mult_id_help(self):
  436. print "Multiple ids can be specified, separated by a space. A range of ids can be specified in the format n-N. e.g. 10-20 would specify all ids from 10 to 20 inclusive."
  437. def help_exit(self):
  438. self.usage("exit")
  439. print "Exits the application."
  440. def help_save(self):
  441. self.usage("save [filename]")
  442. print "Saves the current configuration to [filename]. If no filename is given, the configuration is saved to the file from which the initial configuration was loaded."
  443. def help_set(self):
  444. self.usage("set [configoption] [value]")
  445. print "Sets a configuration option. If no value is specified, the current value for [configoption] is output. If neither [configoption] nor [value] are specified, the whole current configuration is output. [configoption] must be of the format <section>.<option>"
  446. def help_ls(self):
  447. self.help_list()
  448. def help_passwd(self):
  449. self.usage("passwd")
  450. print "Changes the password on the database. "
  451. def help_forget(self):
  452. self.usage("forget")
  453. print "Forgets the database password. Your password will need to be reentered before accessing the database again."
  454. def help_clear(self):
  455. self.usage("clear")
  456. print "Clears the filter criteria. "
  457. def help_filter(self):
  458. self.usage("filter <tag> ...")
  459. print "Filters nodes on tag. Arguments can be zero or more tags. Displays current tags if called without arguments."
  460. def help_tags(self):
  461. self.usage("tags")
  462. print "Displays all tags in used in the database."
  463. def postloop(self):
  464. try:
  465. readline.write_history_file(self._historyfile)
  466. except Exception, e:
  467. pass
  468. def __init__(self, db):
  469. cmd.Cmd.__init__(self)
  470. self.intro = "%s %s (c) %s <%s>" % (pwman.appname, pwman.version,
  471. pwman.author, pwman.authoremail)
  472. self._historyfile = config.get_value("Readline", "history")
  473. try:
  474. enc = CryptoEngine.get()
  475. enc.set_callback(CLICallback())
  476. self._db = db
  477. self._db.open()
  478. except Exception, e:
  479. self.error(e)
  480. sys.exit(1)
  481. try:
  482. readline.read_history_file(self._historyfile)
  483. except Exception, e:
  484. pass
  485. self.prompt = "pwman> "
  486. _defaultwidth = 10
  487. def getonechar(question, width=_defaultwidth):
  488. question = "%s " % (question)
  489. print question.ljust(width),
  490. sys.stdout.flush()
  491. fd = sys.stdin.fileno()
  492. tty_mode = tty.tcgetattr(fd)
  493. tty.setcbreak(fd)
  494. try:
  495. ch = os.read(fd, 1)
  496. finally:
  497. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  498. print ch
  499. return ch
  500. def getyesno(question, defaultyes=False, width=_defaultwidth):
  501. if (defaultyes):
  502. default = "[Y/n]"
  503. else:
  504. default = "[y/N]"
  505. ch = getonechar("%s %s" % (question, default), width)
  506. if (ch == '\n'):
  507. if (defaultyes):
  508. return True
  509. else:
  510. return False
  511. elif (ch == 'y' or ch == 'Y'):
  512. return True
  513. elif (ch == 'n' or ch == 'N'):
  514. return False
  515. else:
  516. return getyesno(question, defaultyes, width)
  517. def getinput(question, default="", completer=None, width=_defaultwidth):
  518. if (not _readline_available):
  519. return raw_input(question.ljust(width))
  520. else:
  521. def defaulter(): readline.insert_text(default)
  522. readline.set_startup_hook(defaulter)
  523. oldcompleter = readline.get_completer()
  524. readline.set_completer(completer)
  525. x = raw_input(question.ljust(width))
  526. readline.set_completer(oldcompleter)
  527. readline.set_startup_hook()
  528. return x
  529. def getpassword(question, width=_defaultwidth, echo=False):
  530. if echo:
  531. print question.ljust(width),
  532. return sys.stdin.readline().rstrip()
  533. else:
  534. while 1:
  535. a1 = getpass.getpass(question.ljust(width))
  536. a2 = getpass.getpass("[Repeat] %s" % (question.ljust(width)))
  537. if a1 == a2:
  538. return a1
  539. else:
  540. print "Passwords don't match. Try again."
  541. def typeset(text, color, bold=False, underline=False):
  542. if not config.get_value("Global", "colors") == 'yes':
  543. return text
  544. if (bold):
  545. bold = "%d;" %(ANSI.Bold)
  546. else:
  547. bold = ""
  548. if (underline):
  549. underline = "%d;" % (ANSI.Underline)
  550. else:
  551. underline = ""
  552. return "\033[%s%s%sm%s\033[%sm" % (bold, underline, color,
  553. text, ANSI.Reset)
  554. def select(question, possible):
  555. for i in range(0, len(possible)):
  556. print ("%d - %-"+str(_defaultwidth)+"s") % (i+1, possible[i])
  557. while 1:
  558. input = getonechar(question)
  559. if input.isdigit() and int(input) in range(1, len(possible)+1):
  560. return possible[int(input)-1]
  561. class CliMenu(object):
  562. def __init__(self):
  563. self.items = []
  564. def add(self, item):
  565. if (isinstance(item, CliMenuItem)):
  566. self.items.append(item)
  567. else:
  568. print item.__class__
  569. def run(self):
  570. while True:
  571. i = 0
  572. for x in self.items:
  573. i = i + 1
  574. current = x.getter()
  575. currentstr = ''
  576. if type(current) == list:
  577. for c in current:
  578. currentstr += ("%s " % (c))
  579. else:
  580. currentstr = current
  581. print ("%d - %-"+str(_defaultwidth)+"s %s") % (i, x.name+":",
  582. currentstr)
  583. print "%c - Finish editing" % ('X')
  584. option = getonechar("Enter your choice:")
  585. try:
  586. # substract 1 because array subscripts start at 1
  587. selection = int(option) - 1
  588. value = self.items[selection].editor(self.items[selection].getter())
  589. self.items[selection].setter(value)
  590. except (ValueError,IndexError):
  591. if (option.upper() == 'X'):
  592. break
  593. print "Invalid selection"
  594. class CliMenuItem(object):
  595. def __init__(self, name, editor, getter, setter):
  596. self.name = name
  597. self.editor = editor
  598. self.getter = getter
  599. self.setter = setter