def main():

    usage = "%prog [options] ACTION"
    epilog = """
ACTION is one of add|modify|remove|print

  add:    add a user record
  modify: modify a user record
  remove: remove a user record
"""
    description = "Tool to manipulate CalendarServer augments XML file"
    version = "%prog v1.0"
    parser = OptionParser(usage=usage, description=description, version=version)
    parser.epilog = epilog
    parser.format_epilog = lambda _:epilog

    parser.add_option("-f", "--file", dest="configfilename",
                      help="caldavd.plist defining Augment Service", metavar="FILE")
    parser.add_option("-u", "--uid", dest="uid",
                      help="OD GUID to manipulate", metavar="UID")
    parser.add_option("-i", "--uidfile", dest="uidfile",
                      help="File containing a list of GUIDs to manipulate", metavar="UIDFILE")
    parser.add_option("-n", "--node", dest="node",
                      help="Partition node to assign to UID", metavar="NODE")
    parser.add_option("-c", "--enable-calendar", action="store_true", dest="enable_calendar",
                      default=True, help="Enable calendaring for this UID: %default")
    parser.add_option("-a", "--enable-addressbooks", action="store_true", dest="enable_addressbook",
                      default=True, help="Enable calendaring for this UID: %default")
    parser.add_option("-s", "--auto-schedule", action="store_true", dest="auto_schedule",
                      default=False, help="Enable auto-schedule for this UID: %default")

    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("incorrect number of arguments")

    observer = StandardIOObserver()
    observer.start()

    #
    # Get configuration
    #
    try:
        loadConfig(options.configfilename)
        setLogLevelForNamespace(None, "warn")

        # Shed privileges
        if config.UserName and config.GroupName and os.getuid() == 0:
            uid = getpwnam(config.UserName).pw_uid
            gid = getgrnam(config.GroupName).gr_gid
            switchUID(uid, uid, gid)

        os.umask(config.umask)

        config.directory = getDirectory()
        autoDisableMemcached(config)
    except ConfigurationError, e:
        usage("Unable to start: %s" % (e,))
def main():

    usage = "%prog [options] MODE"
    epilog = """
MODE is one of primary|secondary|add

  primary:   Create a new primary node (manages main DBs)
  secondary: Create a new secondary node
  add:       Add information for a new partition node on another machine
"""
    description = "Tool to setup CalendarServer partition node configuration files"
    version = "%prog v1.0"
    parser = OptionParser(usage=usage, description=description, version=version)
    parser.epilog = epilog
    parser.format_epilog = lambda _:epilog

    parser.add_option("-c", "--conf", dest="conf",
                      help="Directory where .plist files are stored", metavar="CONF")
    parser.add_option("-n", "--nodeid", dest="nodeid",
                      help="Node ID for this node", metavar="NODEID")
    parser.add_option("-u", "--url", dest="nodeurl",
                      help="URL of node being added", metavar="NODEURL")
    parser.add_option("-p", "--primary", dest="primaryurl",
                      help="URL of primary node", metavar="PRIMARYURL")

    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("incorrect number of arguments")

    # Make sure conf dir has the needed .plist files
    if not os.path.exists(options.conf):
        parser.error("Could not find '%s'" % (options.conf,))
    confdir = os.path.dirname(options.conf)
    if not os.path.exists(os.path.join(confdir, "caldavd-partitioning-primary.plist")):
        parser.error("Could not find caldavd-partitioning-primary.plist in '%s'" % (confdir,))
    if not os.path.exists(os.path.join(confdir, "caldavd-partitioning-secondary.plist")):
        parser.error("Could not find caldavd-partitioning-secondary.plist in '%s'" % (confdir,))

    # Handle each action
    {
        "primary"  : createPrimary,
        "secondary": createSecondary,
        "add"      : addOther,
    }[args[0]](options)
def main():

    usage = "%prog [options] ACTION"
    epilog = """
ACTION is one of init|start|stop|run

  init:   initialize databases
  start:  start postgres daemon
  stop:   stop postgres daemon
  run:    run postgres (non-daemon)
  clean:  remove databases
  
"""
    description = "Tool to manage PostgreSQL"
    version = "%prog v1.0"
    parser = OptionParser(usage=usage, description=description, version=version)
    parser.epilog = epilog
    parser.format_epilog = lambda _:epilog

    parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
                      default=True, help="Use debug logging for PostgreSQL")
    parser.add_option("-d", "--base-dir", dest="basedir",
                      default="%s/../postgresql-8.4.2/_root" % (os.getcwd(),), help="Base directory for PostgreSQL install")

    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("incorrect number of arguments")

    if args[0] == "init":
        doInit(options.basedir)
    elif args[0] == "start":
        doStart(options.basedir)
    elif args[0] == "stop":
        doStop(options.basedir)
    elif args[0] == "run":
        doRun(options.basedir, options.verbose)
    elif args[0] == "clean":
        doClean(options.basedir)
    else:
        parser.error("incorrect argument '%s'" % (args[0],))
Пример #4
0
def handle_arguments():
	from optparse import OptionParser, OptionGroup, OptionValueError
	sys.path.append( os.path.abspath( '..' ) )

	def option_callback(option, opt_str, value, parser, *args, **kwargs):
		pass

	def parse_host(text):
		if "@" in text:
			user = text[:text.index("@")]
			if ":" in text:
				host = text[text.index("@") +1 :text.index(":")]
				port = int(text[text.index(":") +1 :])
			else:
				host = text[text.index("@") +1 :]
				port = options.socks_port
		else:
			user = None
			if ":" in text:
				host = text[:text.index(":")]
				port = int(text[text.index(":") +1 :])
			else:
				host = text
				port = options.socks_port

		return user, host, port

	def check_ssh(option, opt, value, parser):
		try:
			if option.dest == "ssh_host":
				if parser.values.use_socks:
					raise OptionValueError("Cannot use both SSH and SOCKS proxy")
	
			if option.dest == "socks_host":
				if parser.values.use_ssh:
					raise OptionValueError("Cannot use both SSH and SOCKS proxy")
		except AttributeError:
			pass

	def check_socks_host(option, opt, value, parser):
		check_ssh(option, opt, value, parser)
		try:
			u, h, p = parse_host(value)
		except ValueError:
			raise OptionValueError("socks host string is improperly formatted")
		else:
			parser.values.socks_user = u
			parser.values.socks_host = h
			parser.values.socks_port = p
			parser.values.use_socks  = True

	def check_ssh_host(option, opt, value, parser):
		check_ssh(option, opt, value, parser)
		try:
			u, h, p = parse_host(value)
		except ValueError:
			raise OptionValueError("ssh host string is improperly formatted")
		else:
			parser.values.ssh_user = u
			parser.values.ssh_host = h
			parser.values.ssh_port = p
			parser.values.use_ssh  = True
			parser.values.use_socks  = True

	# skip the formatter for the epilog....nice hack.
	def format_epilog(self, formatter):
		import textwrap
		w = ioctl_GWINSZ()[1]
		e = self.epilog.strip()
		lines = []
		[ lines.append(textwrap.fill(l,w).lstrip()) for l in e.split("%") ]
		self.epilog = "\n" + "\n".join(lines) + "\n"
		return self.epilog

	parser = OptionParser()
	ssh_opt = OptionGroup(parser, "SSH/SOCKS Options")
	debug_opt = OptionGroup(parser, "Debug Options")
	parser.add_option_group(ssh_opt)
	parser.add_option_group(debug_opt)

	# just some hack
	instancemethod = type(parser.format_epilog)
	parser.format_epilog = instancemethod(format_epilog, parser, OptionParser)

	# give some more info
	parser.epilog = epilog

	parser.add_option("-a", action="store_true",\
		help="attempt to automatically configure LAN",\
		dest="auto_config")

	parser.add_option("-w", action="store",\
		help="WAN Interface (internet)",\
		type="string", dest="wan_if")

	parser.add_option("-l", action="store",\
		help="LAN Interface (listens for xbox)",\
		type="string", dest="lan_if")

	parser.add_option("-f", action="store_true",\
		help="forward traffic from host (use with care)",\
		dest="forward_host")

	parser.add_option("-c", action="store_true",\
		help="use color for output", dest="use_color")

	parser.add_option("-q",  action="store_true",\
		help="supress output",\
		default=False, dest="quiet")

	debug_opt.add_option("--debug-supress-run",  action="store_true",\
		help="supress the running of commands",\
		default=False, dest="debug_supress_run")

	debug_opt.add_option("-v", action="count",\
		help="more v's for more output",\
		dest="verbosity")

	ssh_opt.add_option("-p", action="callback",\
		help="socks host (see below)",\
		type="string", dest="socks_host", callback=check_socks_host)

	ssh_opt.add_option("-t", action="store",\
		help="type of socks server: 4/5",\
		type="choice", dest="socks_type",\
		choices=["socks4","socks5"])

	ssh_opt.add_option("-s", action="callback",\
		help="ssh host (see below)",\
		type="string", dest="ssh_host", callback=check_ssh_host)

	opt, args = parser.parse_args()

	if opt.verbosity != None:
		opt.verbosity += 2

	if opt.quiet:
		opt.verbosity = 0

	# update the options
	for key, value in opt.__dict__.items():
		if value != None:
			#if hasattr(options, key):
			setattr(options, key, value)
Пример #5
0
 def format_epilog(self, formatter):
     if not self.epilog_formatter_enabled():
         return self.epilog
     return _OptionParser.format_epilog(self, formatter)
Пример #6
0
# TODO: Help should be generated by OptionParser (or better ArgParse)
parser = OptionParser(epilog=docParams)
parser.add_option("-i",
                  "--ifcspec",
                  dest="ifcspec",
                  help="TRAP IFC specifier",
                  metavar="IFCSPEC")
parser.add_option("-d", "--dry-run", action="store_true")
parser.add_option("--skip-smtp-test", action="store_true")
parser.add_option("--limit", metavar="N", type=int, default=20)
parser.add_option("-v",
                  "--verbose",
                  action="store_true",
                  help="Set verbose mode - print messages.")

parser.format_epilog = lambda self: docParams

# Parse the other parameters
opt, args = parser.parse_args()

if not opt.ifcspec:
    print(
        'Usage:\n   python email_reporter.py -i "ifc_spec" [options] CONFIG_FILE'
    )
    exit(1)

if len(args) != 1:
    print(
        'Usage:\n   python email_reporter.py -i "ifc_spec" [options] CONFIG_FILE'
    )
    exit(1)
Пример #7
0
 def format_epilog(self, formatter):
     if not self.epilog_formatter_enabled():
         return self.epilog
     return _OptionParser.format_epilog(self, formatter)
Пример #8
0
   return False


# ********** Parse parameters **********
# TODO: Help should be generated by OptionParser (or better ArgParse)
parser = OptionParser(epilog = docParams)
parser.add_option("-i", "--ifcspec", dest="ifcspec",
      help="TRAP IFC specifier", metavar="IFCSPEC")
parser.add_option("-d", "--dry-run", action="store_true")
parser.add_option("--skip-smtp-test", action="store_true")
parser.add_option("--limit", metavar="N", type=int, default=20)
parser.add_option("-v", "--verbose", action="store_true",
    help="Set verbose mode - print messages.")


parser.format_epilog = lambda self: docParams

# Parse the other parameters
opt, args = parser.parse_args()

if not opt.ifcspec:
    print('Usage:\n   python email_reporter.py -i "ifc_spec" [options] CONFIG_FILE')
    exit(1)

if len(args) != 1:
   print('Usage:\n   python email_reporter.py -i "ifc_spec" [options] CONFIG_FILE')
   exit(1) 

config_file = args[0]

max_msg_per_hour = opt.limit # Maximal number of messages sent per hour