cli.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2012 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  20. #============================================================================
  21. """
  22. Define the CLI interface for pwman3 and the helper functions
  23. """
  24. import pwman
  25. import pwman.exchange.importer as importer
  26. import pwman.exchange.exporter as exporter
  27. import pwman.util.generator as generator
  28. from pwman.data.nodes import Node
  29. from pwman.data.tags import Tag
  30. from pwman.util.crypto import CryptoEngine
  31. #, CryptoBadKeyException, \
  32. # CryptoPasswordMismatchException
  33. from pwman.util.callback import Callback
  34. import pwman.util.config as config
  35. import re
  36. import sys
  37. import os
  38. import struct
  39. import getpass
  40. import cmd
  41. #import traceback
  42. import time
  43. import select as uselect
  44. import subprocess as sp
  45. import ast
  46. if sys.platform != 'win32':
  47. import tty
  48. import termios
  49. import fcntl
  50. try:
  51. import readline
  52. _readline_available = True
  53. except ImportError, e:
  54. _readline_available = False
  55. class CLICallback(Callback):
  56. def getinput(self, question):
  57. return raw_input(question)
  58. def getsecret(self, question):
  59. return getpass.getpass(question + ":")
  60. class ANSI(object):
  61. Reset = 0
  62. Bold = 1
  63. Underscore = 2
  64. Black = 30
  65. Red = 31
  66. Green = 32
  67. Yellow = 33
  68. Blue = 34
  69. Magenta = 35
  70. Cyan = 36
  71. White = 37
  72. class PwmanCli(cmd.Cmd):
  73. def error(self, exception):
  74. if (isinstance(exception, KeyboardInterrupt)):
  75. print
  76. else:
  77. # traceback.print_exc()
  78. print "Error: %s " % (exception)
  79. def do_EOF(self, args):
  80. return self.do_exit(args)
  81. def do_exit(self, args):
  82. print
  83. #try:
  84. # print "goodbye"
  85. self._db.close()
  86. #except DatabaseException, e:
  87. # self.error(e)
  88. return True
  89. def get_ids(self, args):
  90. ids = []
  91. rex = re.compile(r"^(\d+)-(\d+)$")
  92. idstrs = args.split()
  93. for i in idstrs:
  94. m = rex.match(i)
  95. if m == None:
  96. try:
  97. ids.append(int(i))
  98. except ValueError:
  99. self._db.clearfilter()
  100. self._db.filter([Tag(i)])
  101. ids += self._db.listnodes()
  102. else:
  103. ids += range(int(m.group(1)),
  104. int(m.group(2))+1)
  105. return ids
  106. def get_filesystem_path(self, default=""):
  107. return getinput("Enter filename: ", default)
  108. def get_username(self, default=""):
  109. return getinput("Username: ", default)
  110. def get_password(self, argsgiven, numerics=False,leetify=False, symbols=False,
  111. special_signs=False):
  112. """
  113. in the config file:
  114. numerics -> numerics
  115. leetify -> symbols
  116. special_chars -> special_signs
  117. """
  118. if argsgiven == 1:
  119. length = getinput("Password length (default 7): ", "7")
  120. length = int(length)
  121. (password, dumpme) = generator.generate_password(length, length, \
  122. True, leetify, numerics, special_signs)
  123. print "New password: %s" % (password)
  124. return password
  125. # no args given
  126. password = getpassword("Password (Blank to generate): ", _defaultwidth, \
  127. False)
  128. if len(password) == 0:
  129. length = getinput("Password length (default 7): ", "7")
  130. length = int(length)
  131. (password, dumpme) = generator.generate_password(length, length, \
  132. True, leetify, numerics, special_signs)
  133. print "New password: %s" % (password)
  134. return password
  135. def get_url(self, default=""):
  136. return getinput("Url: ", default)
  137. def get_notes(self, default=""):
  138. return getinput("Notes: ", default)
  139. def get_tags(self, default=None):
  140. defaultstr = ''
  141. if default:
  142. for t in default:
  143. defaultstr += "%s " % (t.get_name())
  144. else:
  145. tags = self._db.currenttags()
  146. for t in tags:
  147. defaultstr += "%s " % (t.get_name())
  148. strings = []
  149. tags = self._db.listtags(True)
  150. for t in tags:
  151. strings.append(t.get_name())
  152. def complete(text, state):
  153. count = 0
  154. for s in strings:
  155. if s.startswith(text):
  156. if count == state:
  157. return s
  158. else:
  159. count += 1
  160. taglist = getinput("Tags: ", defaultstr, complete)
  161. tagstrings = taglist.split()
  162. tags = []
  163. for tn in tagstrings:
  164. tags.append(Tag(tn))
  165. return tags
  166. def print_node(self, node):
  167. width = str(_defaultwidth)
  168. print "Node %d." % (node.get_id())
  169. print ("%"+width+"s %s") % (typeset("Username:", ANSI.Red),
  170. node.get_username())
  171. print ("%"+width+"s %s") % (typeset("Password:", ANSI.Red),
  172. node.get_password())
  173. print ("%"+width+"s %s") % (typeset("Url:", ANSI.Red),
  174. node.get_url())
  175. print ("%"+width+"s %s") % (typeset("Notes:", ANSI.Red),
  176. node.get_notes())
  177. print typeset("Tags: ", ANSI.Red),
  178. for t in node.get_tags():
  179. print " %s " % t.get_name(),
  180. print
  181. def heardEnter():
  182. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  183. for s in i:
  184. if s == sys.stdin:
  185. sys.stdin.readline()
  186. return True
  187. return False
  188. def heardEnterWin():
  189. import msvcrt
  190. c = msvcrt.kbhit()
  191. if c == 1:
  192. ret = msvcrt.getch()
  193. if ret is not None:
  194. return True
  195. return False
  196. def waituntil_enter(somepredicate, timeout, period=0.25):
  197. mustend = time.time() + timeout
  198. while time.time() < mustend:
  199. cond = somepredicate()
  200. if cond:
  201. break
  202. time.sleep(period)
  203. self.do_cls('')
  204. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  205. if flushtimeout > 0:
  206. if sys.platform != 'win32':
  207. print "Type Enter to flush screen (autoflash in 5 sec.)"
  208. waituntil_enter(heardEnter, flushtimeout)
  209. else:
  210. print "Press any key to flush screen (autoflash in 5 sec.)"
  211. waituntil_enter(heardEnterWin, flushtimeout)
  212. def do_tags(self, arg):
  213. tags = self._db.listtags()
  214. if len(tags) > 0:
  215. tags[0].get_name() # hack to get password request before output
  216. print "Tags: ",
  217. if len(tags) == 0:
  218. print "None",
  219. for t in tags:
  220. print "%s " % (t.get_name()),
  221. print
  222. def complete_filter(self, text, line, begidx, endidx):
  223. strings = []
  224. enc = CryptoEngine.get()
  225. if not enc.alive():
  226. return strings
  227. tags = self._db.listtags()
  228. for t in tags:
  229. name = t.get_name()
  230. if name.startswith(text):
  231. strings.append(t.get_name())
  232. return strings
  233. def do_filter(self, args):
  234. tagstrings = args.split()
  235. try:
  236. tags = []
  237. for ts in tagstrings:
  238. tags.append(Tag(ts))
  239. self._db.filter(tags)
  240. tags = self._db.currenttags()
  241. print "Current tags: ",
  242. if len(tags) == 0:
  243. print "None",
  244. for t in tags:
  245. print "%s " % (t.get_name()),
  246. print
  247. except Exception, e:
  248. self.error(e)
  249. def do_clear(self, args):
  250. try:
  251. self._db.clearfilter()
  252. except Exception, e:
  253. self.error(e)
  254. def do_e(self, arg):
  255. self.do_edit(arg)
  256. def do_edit(self, arg):
  257. ids = self.get_ids(arg)
  258. for i in ids:
  259. try:
  260. i = int(i)
  261. node = self._db.getnodes([i])[0]
  262. menu = CliMenu()
  263. print "Editing node %d." % (i)
  264. menu.add(CliMenuItem("Username", self.get_username,
  265. node.get_username,
  266. node.set_username))
  267. menu.add(CliMenuItem("Password", self.get_password,
  268. node.get_password,
  269. node.set_password))
  270. menu.add(CliMenuItem("Url", self.get_url,
  271. node.get_url,
  272. node.set_url))
  273. menu.add(CliMenuItem("Notes", self.get_notes,
  274. node.get_notes,
  275. node.set_notes))
  276. menu.add(CliMenuItem("Tags", self.get_tags,
  277. node.get_tags,
  278. node.set_tags))
  279. menu.run()
  280. self._db.editnode(i, node)
  281. except Exception, e:
  282. self.error(e)
  283. def do_import(self, arg):
  284. try:
  285. args = arg.split()
  286. if len(args) == 0:
  287. types = importer.Importer.types()
  288. intype = select("Select filetype:", types)
  289. imp = importer.Importer.get(intype)
  290. infile = getinput("Select file:")
  291. imp.import_data(self._db, infile)
  292. else:
  293. for i in args:
  294. types = importer.Importer.types()
  295. intype = select("Select filetype:", types)
  296. imp = importer.Importer.get(intype)
  297. imp.import_data(self._db, i)
  298. except Exception, e:
  299. self.error(e)
  300. def do_export(self, arg):
  301. try:
  302. nodes = self.get_ids(arg)
  303. types = exporter.Exporter.types()
  304. ftype = select("Select filetype:", types)
  305. exp = exporter.Exporter.get(ftype)
  306. out_file = getinput("Select output file:")
  307. if len(nodes) > 0:
  308. b = getyesno("Export nodes %s?" % (nodes), True)
  309. if not b:
  310. return
  311. exp.export_data(self._db, out_file, nodes)
  312. else:
  313. nodes = self._db.listnodes()
  314. tags = self._db.currenttags()
  315. tagstr = ""
  316. if len(tags) > 0:
  317. tagstr = " for "
  318. for t in tags:
  319. tagstr += "'%s' " % (t.get_name())
  320. b = getyesno("Export all nodes%s?" % (tagstr), True)
  321. if not b:
  322. return
  323. exp.export_data(self._db, out_file, nodes)
  324. print "Data exported."
  325. except Exception, e:
  326. self.error(e)
  327. def do_h(self, arg):
  328. self.do_help(arg)
  329. def do_n(self, arg):
  330. self.do_new(arg)
  331. def do_new(self, args):
  332. """
  333. can override default config settings the following way:
  334. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  335. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  336. Password (Blank to generate):
  337. """
  338. errmsg = """could not parse config override, please input some"""\
  339. +""" kind of dictionary, e.g.: n {'leetify':False, """\
  340. +"""'numerics':True, 'special_chars':True}"""
  341. try:
  342. username = self.get_username()
  343. if args:
  344. try:
  345. args = ast.literal_eval(args)
  346. except Exception:
  347. raise Exception(errmsg)
  348. if not isinstance(args, dict):
  349. raise Exception(errmsg)
  350. password = self.get_password(1, **args)
  351. else:
  352. numerics = config.get_value("Generator", "numerics").lower() == 'true'
  353. # TODO: allow custom leetifying through the config
  354. leetify = config.get_value("Generator", "leetify").lower() == 'true'
  355. special_chars = config.get_value("Generator", "special_chars").lower() == 'true'
  356. password = self.get_password(0,
  357. numerics=numerics,
  358. symbols=leetify,
  359. special_signs=special_chars)
  360. url = self.get_url()
  361. notes = self.get_notes()
  362. node = Node(username, password, url, notes)
  363. tags = self.get_tags()
  364. node.set_tags(tags)
  365. self._db.addnodes([node])
  366. print "Password ID: %d" % (node.get_id())
  367. except Exception, e:
  368. self.error(e)
  369. def do_p(self, arg):
  370. self.do_print(arg)
  371. def do_print(self, arg):
  372. for i in self.get_ids(arg):
  373. try:
  374. node = self._db.getnodes([i])
  375. self.print_node(node[0])
  376. except Exception, e:
  377. self.error(e)
  378. def do_rm(self, arg):
  379. self.do_delete(arg)
  380. def do_delete(self, arg):
  381. ids = self.get_ids(arg)
  382. try:
  383. nodes = self._db.getnodes(ids)
  384. for n in nodes:
  385. b = getyesno("Are you sure you want to delete '%s@%s'?"
  386. % (n.get_username(), n.get_url()), False)
  387. if b == True:
  388. self._db.removenodes([n])
  389. print "%s@%s deleted" % (n.get_username(), n.get_url())
  390. except Exception, e:
  391. self.error(e)
  392. def do_l(self, args):
  393. self.do_list(args)
  394. def do_ls(self, args):
  395. self.do_list(args)
  396. def do_list(self, args):
  397. if len(args.split()) > 0:
  398. self.do_clear('')
  399. self.do_filter(args)
  400. try:
  401. if sys.platform != 'win32':
  402. rows, cols = gettermsize()
  403. else:
  404. rows, cols = 18, 80 # fix this !
  405. nodeids = self._db.listnodes()
  406. nodes = self._db.getnodes(nodeids)
  407. cols -= 8
  408. i = 0
  409. for n in nodes:
  410. tags = n.get_tags()
  411. tagstring = ''
  412. first = True
  413. for t in tags:
  414. if not first:
  415. tagstring += ", "
  416. else:
  417. first = False
  418. tagstring += t.get_name()
  419. name = "%s@%s" % (n.get_username(), n.get_url())
  420. name_len = cols * 2 / 3
  421. tagstring_len = cols / 3
  422. if len(name) > name_len:
  423. name = name[:name_len-3] + "..."
  424. if len(tagstring) > tagstring_len:
  425. tagstring = tagstring[:tagstring_len-3] + "..."
  426. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  427. print typeset(fmt % (n.get_id(), name, tagstring),
  428. ANSI.Yellow, False)
  429. i += 1
  430. if i > rows-2:
  431. i = 0
  432. c = getonechar("Press <Space> for more, or 'Q' to cancel")
  433. if c == 'q':
  434. break
  435. except Exception, e:
  436. self.error(e)
  437. def do_forget(self, args):
  438. try:
  439. enc = CryptoEngine.get()
  440. enc.forget()
  441. except Exception, e:
  442. self.error(e)
  443. def do_passwd(self, args):
  444. try:
  445. self._db.changepassword()
  446. except Exception, e:
  447. self.error(e)
  448. def do_set(self, args):
  449. argstrs = args.split()
  450. try:
  451. if len(argstrs) == 0:
  452. conf = config.get_conf()
  453. for s in conf.keys():
  454. for n in conf[s].keys():
  455. print "%s.%s = %s" % (s, n, conf[s][n])
  456. elif len(argstrs) == 1:
  457. r = re.compile("(.+)\.(.+)")
  458. m = r.match(argstrs[0])
  459. if m is None or len(m.groups()) != 2:
  460. print "Invalid option format"
  461. self.help_set()
  462. return
  463. print "%s.%s = %s" % (m.group(1), m.group(2),
  464. config.get_value(m.group(1), m.group(2)))
  465. elif len(argstrs) == 2:
  466. r = re.compile("(.+)\.(.+)")
  467. m = r.match(argstrs[0])
  468. if m is None or len(m.groups()) != 2:
  469. print "Invalid option format"
  470. self.help_set()
  471. return
  472. config.set_value(m.group(1), m.group(2), argstrs[1])
  473. else:
  474. self.help_set()
  475. except Exception, e:
  476. self.error(e)
  477. def do_save(self, args):
  478. argstrs = args.split()
  479. try:
  480. if len(argstrs) > 0:
  481. config.save(argstrs[0])
  482. else:
  483. config.save()
  484. print "Config saved."
  485. except Exception, e:
  486. self.error(e)
  487. def do_cls(self, args):
  488. os.system('clear')
  489. def do_copy(self, args):
  490. if self.hasxsel:
  491. ids = self.get_ids(args)
  492. if len(ids) > 1:
  493. print "Can copy only 1 password at a time..."
  494. return None
  495. try:
  496. node = self._db.getnodes(ids)
  497. text_to_clipboards(node[0].get_password())
  498. print "copied password for %s@%s clipboard... erasing in 10 sec..." % \
  499. (node[0].get_username(), node[0].get_url())
  500. time.sleep(10)
  501. text_to_clipboards("")
  502. except Exception, e:
  503. self.error(e)
  504. else:
  505. print "Can't copy to clipboard, no xsel found in the system!"
  506. def do_cp(self, args):
  507. self.do_copy(args)
  508. def do_open(self, args):
  509. ids = self.get_ids(args)
  510. if len(ids) > 1:
  511. print "Can open only 1 link at a time ..."
  512. return None
  513. try:
  514. node = self._db.getnodes(ids)
  515. url = node[0].get_url()
  516. open_url(url)
  517. except Exception, e:
  518. self.error(e)
  519. def do_o(self, args):
  520. self.do_open(args)
  521. ##
  522. ## Help functions
  523. ##
  524. def usage(self, string):
  525. print "Usage: %s" % (string)
  526. def help_open(self):
  527. self.usage("open <ID>")
  528. print "Launch default browser with 'xdg-open url',\n\
  529. the url must contain http:// or https://."
  530. def help_o(self):
  531. self.help_open()
  532. def help_copy(self):
  533. self.usage("copy <ID>")
  534. print "Copy password to X clipboard (xsel required)"
  535. def help_cp(self):
  536. self.help_copy()
  537. def help_cls(self):
  538. self.usage("cls")
  539. print "Clear the Screen from information."
  540. def help_list(self):
  541. self.usage("list <tag> ...")
  542. print "List nodes that match current or specified filter. ls is an alias."
  543. def help_EOF(self):
  544. self.help_exit()
  545. def help_delete(self):
  546. self.usage("delete <ID|tag> ...")
  547. print "Deletes nodes. rm is an alias."
  548. self._mult_id_help()
  549. def help_h(self):
  550. self.help_help()
  551. def help_help(self):
  552. self.usage("help [topic]")
  553. print "Prints a help message for a command."
  554. def help_e(self):
  555. self.help_edit()
  556. def help_n(self):
  557. self.help_new()
  558. def help_p(self):
  559. self.help_print()
  560. def help_l(self):
  561. self.help_list()
  562. def help_edit(self):
  563. self.usage("edit <ID|tag> ... ")
  564. print "Edits a nodes."
  565. self._mult_id_help()
  566. def help_import(self):
  567. self.usage("import [filename] ...")
  568. print "Imports a nodes from a file."
  569. def help_export(self):
  570. self.usage("export <ID|tag> ... ")
  571. 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."
  572. self._mult_id_help()
  573. def help_new(self):
  574. self.usage("new")
  575. print """Creates a new node.,
  576. You can override default config settings the following way:
  577. pwman> n {'leetify':False, 'numerics':True}"""
  578. def help_rm(self):
  579. self.help_delete()
  580. def help_print(self):
  581. self.usage("print <ID|tag> ...")
  582. print "Displays a node. ",
  583. self._mult_id_help()
  584. def _mult_id_help(self):
  585. 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'."
  586. def help_exit(self):
  587. self.usage("exit")
  588. print "Exits the application."
  589. def help_save(self):
  590. self.usage("save [filename]")
  591. print "Saves the current configuration to [filename]. If no filename is given, the configuration is saved to the file from which the initial configuration was loaded."
  592. def help_set(self):
  593. self.usage("set [configoption] [value]")
  594. 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>"
  595. def help_passwd(self):
  596. self.usage("passwd")
  597. print "Changes the password on the database. "
  598. def help_forget(self):
  599. self.usage("forget")
  600. print "Forgets the database password. Your password will need to be reentered before accessing the database again."
  601. def help_clear(self):
  602. self.usage("clear")
  603. print "Clears the filter criteria. "
  604. def help_filter(self):
  605. self.usage("filter <tag> ...")
  606. print "Filters nodes on tag. Arguments can be zero or more tags. Displays current tags if called without arguments."
  607. def help_tags(self):
  608. self.usage("tags")
  609. print "Displays all tags in used in the database."
  610. def postloop(self):
  611. try:
  612. readline.write_history_file(self._historyfile)
  613. except Exception:
  614. pass
  615. def __init__(self, db, hasxsel):
  616. """
  617. initialize CLI interface, set up the DB
  618. connecion, see if we have xsel ...
  619. """
  620. cmd.Cmd.__init__(self)
  621. self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version,
  622. pwman.website)
  623. self._historyfile = config.get_value("Readline", "history")
  624. self.hasxsel = hasxsel
  625. try:
  626. enc = CryptoEngine.get()
  627. enc.set_callback(CLICallback())
  628. self._db = db
  629. self._db.open()
  630. except Exception, e:
  631. self.error(e)
  632. sys.exit(1)
  633. try:
  634. readline.read_history_file(self._historyfile)
  635. except IOError, e:
  636. pass
  637. self.prompt = "pwman> "
  638. class PwmanCliMac(PwmanCli):
  639. """
  640. inherit from PwmanCli, override the right functions...
  641. """
  642. def do_copy(self, args):
  643. ids = self.get_ids(args)
  644. if len(ids) > 1:
  645. print "Can only 1 password at a time..."
  646. try:
  647. node = self._db.getnodes(ids)
  648. node[0].get_password()
  649. text_to_mcclipboard(node[0].get_password())
  650. print "copied password for %s@%s clipboard... erasing in 10 sec..." % \
  651. (node[0].get_username(), node[0].get_url())
  652. time.sleep(10)
  653. text_to_clipboards("")
  654. except Exception, e:
  655. self.error(e)
  656. def do_cp(self, args):
  657. self.do_copy(args)
  658. def do_open(self, args):
  659. ids = self.get_ids(args)
  660. if len(ids) > 1:
  661. print "Can open only 1 link at a time ..."
  662. return None
  663. try:
  664. node = self._db.getnodes(ids)
  665. url = node[0].get_url()
  666. open_url(url, macosx=True)
  667. except Exception, e:
  668. self.error(e)
  669. def do_o(self, args):
  670. self.do_open(args)
  671. ##
  672. ## Help functions
  673. ##
  674. def help_open(self):
  675. self.usage("open <ID>")
  676. print "Launch default browser with 'open url',\n\
  677. the url must contain http:// or https://."
  678. def help_o(self):
  679. self.help_open()
  680. def help_copy(self):
  681. self.usage("copy <ID>")
  682. print "Copy password to Cocoa clipboard using pbcopy)"
  683. def help_cp(self):
  684. self.help_copy()
  685. _defaultwidth = 10
  686. def getonechar(question, width=_defaultwidth):
  687. question = "%s " % (question)
  688. print question.ljust(width),
  689. sys.stdout.flush()
  690. fd = sys.stdin.fileno()
  691. tty_mode = tty.tcgetattr(fd)
  692. tty.setcbreak(fd)
  693. try:
  694. ch = os.read(fd, 1)
  695. finally:
  696. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  697. print ch
  698. return ch
  699. def getyesno(question, defaultyes=False, width=_defaultwidth):
  700. if (defaultyes):
  701. default = "[Y/n]"
  702. else:
  703. default = "[y/N]"
  704. ch = getonechar("%s %s" % (question, default), width)
  705. if (ch == '\n'):
  706. if (defaultyes):
  707. return True
  708. else:
  709. return False
  710. elif (ch == 'y' or ch == 'Y'):
  711. return True
  712. elif (ch == 'n' or ch == 'N'):
  713. return False
  714. else:
  715. return getyesno(question, defaultyes, width)
  716. def gettermsize():
  717. s = struct.pack("HHHH", 0, 0, 0, 0)
  718. f = sys.stdout.fileno()
  719. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  720. rows, cols, width, height = struct.unpack("HHHH", x)
  721. return rows, cols
  722. def getinput(question, default="", completer=None, width=_defaultwidth):
  723. if (not _readline_available):
  724. return raw_input(question.ljust(width))
  725. else:
  726. def defaulter():
  727. """define default behavior startup"""
  728. readline.insert_text(default)
  729. readline.set_startup_hook(defaulter)
  730. oldcompleter = readline.get_completer()
  731. readline.set_completer(completer)
  732. x = raw_input(question.ljust(width))
  733. readline.set_completer(oldcompleter)
  734. readline.set_startup_hook()
  735. return x
  736. def getpassword(question, width=_defaultwidth, echo=False):
  737. if echo:
  738. print question.ljust(width),
  739. return sys.stdin.readline().rstrip()
  740. else:
  741. while 1:
  742. a1 = getpass.getpass(question.ljust(width))
  743. if len(a1) == 0:
  744. return a1
  745. a2 = getpass.getpass("[Repeat] %s" % (question.ljust(width)))
  746. if a1 == a2:
  747. return a1
  748. else:
  749. print "Passwords don't match. Try again."
  750. def typeset(text, color, bold=False, underline=False):
  751. if not config.get_value("Global", "colors") == 'yes':
  752. return text
  753. if (bold):
  754. bold = "%d ;" % (ANSI.Bold)
  755. else:
  756. bold = ""
  757. if (underline):
  758. underline = "%d;" % (ANSI.Underscore)
  759. else:
  760. underline = ""
  761. return "\033[%s%s%sm%s\033[%sm" % (bold, underline, color,
  762. text, ANSI.Reset)
  763. def select(question, possible):
  764. for i in range(0, len(possible)):
  765. print ("%d - %-"+str(_defaultwidth)+"s") % (i+1, possible[i])
  766. while 1:
  767. uinput = getonechar(question)
  768. if uinput.isdigit() and int(uinput) in range(1, len(possible)+1):
  769. return possible[int(uinput)-1]
  770. def text_to_clipboards(text):
  771. """
  772. copy text to clipboard
  773. credit:
  774. https://pythonadventures.wordpress.com/tag/xclip/
  775. """
  776. # "primary":
  777. try:
  778. xsel_proc = sp.Popen(['xsel', '-pi'], stdin=sp.PIPE)
  779. xsel_proc.communicate(text)
  780. # "clipboard":
  781. xsel_proc = sp.Popen(['xsel', '-bi'], stdin=sp.PIPE)
  782. xsel_proc.communicate(text)
  783. except OSError, e:
  784. print e, "\nExecuting xsel failed, is it installed ?\n \
  785. please check your configuration file ... "
  786. def text_to_mcclipboard(text):
  787. """
  788. copy text to mac os x clip board
  789. credit:
  790. https://pythonadventures.wordpress.com/tag/xclip/
  791. """
  792. # "primary":
  793. try:
  794. pbcopy_proc = sp.Popen(['pbcopy'], stdin=sp.PIPE)
  795. pbcopy_proc.communicate(text)
  796. except OSError, e:
  797. print e, "\nExecuting pbcoy failed..."
  798. def open_url(link, macosx=False):
  799. """
  800. launch xdg-open or open in MacOSX with url
  801. """
  802. uopen = "xdg-open"
  803. if macosx:
  804. uopen = "open"
  805. try:
  806. sp.Popen([uopen, link], stdin=sp.PIPE)
  807. except OSError, e:
  808. print "Executing open_url failed with:\n", e
  809. class CliMenu(object):
  810. def __init__(self):
  811. self.items = []
  812. def add(self, item):
  813. if (isinstance(item, CliMenuItem)):
  814. self.items.append(item)
  815. else:
  816. print item.__class__
  817. def run(self):
  818. while True:
  819. i = 0
  820. for x in self.items:
  821. i = i + 1
  822. current = x.getter()
  823. currentstr = ''
  824. if type(current) == list:
  825. for c in current:
  826. currentstr += ("%s " % (c))
  827. else:
  828. currentstr = current
  829. print ("%d - %-"+str(_defaultwidth)+"s %s") % (i, x.name+":",
  830. currentstr)
  831. print "%c - Finish editing" % ('X')
  832. option = getonechar("Enter your choice:")
  833. try:
  834. # substract 1 because array subscripts start at 0
  835. selection = int(option) - 1
  836. print "selection, ", selection
  837. # new value is created by calling the editor with the
  838. # previous value as a parameter
  839. # TODO: enable overriding password policy as if new node
  840. # is created.
  841. if selection == 1: # for password
  842. value = self.items[selection].editor(0)
  843. else:
  844. value = self.items[selection].editor(self.items[selection].getter())
  845. self.items[selection].setter(value)
  846. except (ValueError, IndexError):
  847. if (option.upper() == 'X'):
  848. break
  849. print "Invalid selection"
  850. class CliMenuItem(object):
  851. def __init__(self, name, editor, getter, setter):
  852. self.name = name
  853. self.editor = editor
  854. self.getter = getter
  855. self.setter = setter