cli.py 28 KB

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