cli.py 28 KB

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