cli.py 36 KB

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