cli.py 22 KB

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