cli.py 22 KB

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