Python os.EX_USAGE() Examples

The following are code examples for showing how to use os.EX_USAGE(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: redisrwlock   Author: veshboo   File: test_redisrwlock_cmdline.py    (license) View Source Project 6 votes vote down vote up
def test_option_repeat_interval(self):
        """test --retry and --interval options"""
        # run with --retry, see 2 lines, then kill -INT
        cmd, output = runCmdOutput(['-p', '7788', '-r'],
                                   wait=False, limit=2)
        cmd.send_signal(signal.SIGINT)
        self.assertEqual(cmd.wait(), 1)
        cmd.stdout.close()
        # run with --retry, see 4 lines, then kill -INT
        cmd, output = runCmdOutput(['-p', '7788', '-r', '-i', '1'],
                                   wait=False, limit=4)
        cmd.send_signal(signal.SIGINT)
        self.assertEqual(cmd.wait(), 1)
        cmd.stdout.close()
        # invalid --interval option argument (int > 0)
        cmd, output = runCmdOutput(['-p', '7788', '-i', '0'])
        self.assertEqual(cmd.returncode, os.EX_USAGE)
        # --interval option argument ignored if no --retry
        cmd, output = runCmdOutput(['-p', '7788', '-i', '1000'])
        self.assertEqual(cmd.returncode, os.EX_OK) 
Example 2
Project: thefuzz   Author: droberson   File: FuzzTCPClient.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, server, port):
        self.server = server
        self.port = port
        self.fuzz_queue = Queue.Queue()
        self.header = None

        # Validate IP address
        try:
            socket.inet_aton(server)
        except socket.error:
            print "[-] Invalid IP address: %s" % server
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        # Validate port number
        if port > 65535 or port < 1:
            print "[-] Invalid port number: %d" % port
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        # Create client socket
        self.client = None 
Example 3
Project: pyrate-build   Author: pyrate-build   File: pyrate.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def main():
	version_info = 'pyrate version ' + __version__
	try:
		if os.environ.get('TESTOLDIMPORTS'):
			raise ImportError()
		import argparse
		parser = argparse.ArgumentParser()
		parser.add_argument('build_file', nargs = '?', default = 'build.py',
			help = 'name of the input file - default: build.py')
		parser.add_argument('-V', '--version', action = 'version', version = version_info)
		parser.add_argument('-M', '--makefile', action = 'store_true', help = 'enable makefile mode')
		parser.add_argument('-o', '--output', nargs = 1, default = None,
			help = 'name of output build file')
		args = parser.parse_args()
		if args.output:
			args.output = args.output[0]
		bfn = args.build_file
	except ImportError:
		optparse = __import__('optparse')
		parser = optparse.OptionParser(usage = 'pyrate [options] build_file')
		parser.add_option('-V', '--version', action='store_true', help = 'display version')
		parser.add_option('-M', '--makefile', action = 'store_true', help = 'enable makefile mode')
		parser.add_option('-o', '--output', default = None,
			help = 'name of output build file', dest='output')
		(args, posargs) = parser.parse_args()
		if len(posargs) > 1:
			sys.stderr.write('too many build_file arguments provided! %s\n' % repr(posargs))
			return os.EX_USAGE
		elif not posargs:
			posargs = ['build.py']
		bfn = posargs[0]
		if args.version:
			sys.stderr.write(version_info + '\n')
			sys.exit(os.EX_OK)

	generate_build_file(bfn, args.output, args.makefile)

################################################################################
# Externals + helper functions
################################################################################ 
Example 4
Project: redisrwlock   Author: veshboo   File: test_redisrwlock_cmdline.py    (license) View Source Project 5 votes vote down vote up
def test_option_unrecognized(self):
        """test usage error for unrecognized option"""
        cmd, output = runCmdOutput(['--unrecognized'])
        self.assertEqual(cmd.returncode, os.EX_USAGE) 
Example 5
Project: redisrwlock   Author: veshboo   File: test_redisrwlock_cmdline.py    (license) View Source Project 5 votes vote down vote up
def test_option_unhandled(self):
        """test not handled option with hidden test option"""
        cmd, output = runCmdOutput(['--__unhandled__'])
        self.assertEqual(cmd.returncode, os.EX_USAGE) 
Example 6
Project: redisrwlock   Author: veshboo   File: test_redisrwlock_cmdline.py    (license) View Source Project 5 votes vote down vote up
def test_option_server_port(self):
        """test --server and --port options"""
        # empty redis-server host name
        cmd, output = runCmdOutput(['-s', '', '-p', '7788'])
        self.assertEqual(cmd.returncode, os.EX_USAGE)
        # port number out of range
        cmd, output = runCmdOutput(['-s', 'localhost', '-p', '99999'])
        self.assertEqual(cmd.returncode, os.EX_USAGE) 
Example 7
Project: pytypes   Author: Stewori   File: stubfile_2_converter.py    (license) View Source Project 5 votes vote down vote up
def err_no_in_file():
    print("Error: No in_file given! Use -h for help.")
    sys.exit(os.EX_USAGE) 
Example 8
Project: jipdate   Author: Linaro   File: jipdate.py    (license) View Source Project 5 votes vote down vote up
def main(argv):
    parser = get_parser()

    # The parser arguments (cfg.args) are accessible everywhere after this call.
    cfg.args = parser.parse_args()

    # This initiates the global yml configuration instance so it will be
    # accessible everywhere after this call.
    cfg.initiate_config()

    if not cfg.args.file and not cfg.args.q:
        eprint("No file provided and not in query mode\n")
        parser.print_help()
        sys.exit(os.EX_USAGE)

    jira, username = jiralogin.get_jira_instance(cfg.args.t)

    if cfg.args.x or cfg.args.e:
        if not cfg.args.q:
            eprint("Arguments '-x' and '-e' can only be used together with '-q'")
            sys.exit(os.EX_USAGE)

    if cfg.args.p and not cfg.args.q:
        eprint("Arguments '-p' can only be used together with '-q'")
        sys.exit(os.EX_USAGE)

    if cfg.args.q:
        filename = get_jira_issues(jira, username)

        if cfg.args.p:
            print_status_file(filename)
            sys.exit(os.EX_OK)
    elif cfg.args.file is not None:
        filename = cfg.args.file
    else:
        eprint("Trying to run script with unsupported configuration. Try using --help.")
        sys.exit(os.EX_USAGE)

    if get_editor():
        open_editor(filename)
    parse_status_file(jira, filename) 
Example 9
Project: sshady   Author: droberson   File: sshady.py    (license) View Source Project 5 votes vote down vote up
def sigint_handler(signum, frame):
    """ sigint_handler() -- Generic SIGINT handler
    """
    xprint("[-] Caught SIGINT.")
    xprint("[-] Exiting..")
    exit(os.EX_USAGE) 
Example 10
Project: thefuzz   Author: droberson   File: FuzzTCPServer.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, bindaddr="0.0.0.0", port=4444, backlog=5):
        self.inputs = []
        self.outputs = []
        self.clientmap = {}
        self.banner = None

        self.fuzz_queue = Queue.Queue()

        # Validate IP address
        try:
            socket.inet_aton(bindaddr)
        except socket.error:
            print "[-] Invalid bindaddr: %s" % bindaddr
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        # Validate port number
        if port > 65535 or port < 1:
            print "[-] Invalid port number: %d" % port
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        # Create listen socket
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server.setblocking(0)

        # bind to port
        try:
            self.server.bind((bindaddr, port))
        except socket.error, exp:
            print "[-] Unable to bind to %s:%d: %s" % (bindaddr, port, exp)
            print "[-] Exiting."
            sys.exit(os.EX_USAGE)

        print "[+] Listening on %s:%d" % (bindaddr, port)
        self.server.listen(backlog)

        signal.signal(signal.SIGINT, self.siginthandler) 
Example 11
Project: redisrwlock   Author: veshboo   File: __main__.py    (license) View Source Project 4 votes vote down vote up
def main():
    # Default values
    opt_repeat = False
    opt_interval = 5
    opt_server = "localhost"
    opt_port = 6379
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            "hVri:s:p:",
            ["help", "version", "repeat", "interval=", "server=", "port=",
             "__unhandled__"])
    except getopt.GetoptError as err:
        print("ERROR:", err)
        sys.exit(os.EX_USAGE)
    for opt, opt_arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-V", "--version"):
            version()
            sys.exit()
        elif opt in ("-r", "--repeat"):
            opt_repeat = True
        elif opt in ("-i", "--interval"):
            try:
                opt_interval = int(opt_arg)
                if opt_interval == 0:
                    raise ValueError
            except:
                print("ERROR: specify interval as number of seconds")
                sys.exit(os.EX_USAGE)
        elif opt in ("-s", "--server"):
            opt_server = opt_arg
            if len(opt_server) == 0:
                print("ERROR: specify host name or address of redis-server")
                sys.exit(os.EX_USAGE)
        elif opt in ("-p", "--port"):
            try:
                opt_port = int(opt_arg)
                if not 0 <= opt_port <= 65535:
                    raise ValueError
            except:
                print("ERROR: specify port as number in [0, 65535]")
                sys.exit(os.EX_USAGE)
        else:
            print("ERROR: unhandled option")
            sys.exit(os.EX_USAGE)
    logging_config()
    logger = logging.getLogger(__name__)
    # Gc periodically
    client = RwlockClient(StrictRedis(host=opt_server, port=opt_port))
    while True:
        logger.info('redisrwlock gc')
        client.gc()
        if not opt_repeat:
            break
        time.sleep(opt_interval) 
Example 12
Project: sshady   Author: droberson   File: sshady.py    (license) View Source Project 4 votes vote down vote up
def main():
    """ main() -- entry point of program

    Args:
        None

    Returns:
        os.EX_OK on successful run
        os_EX_USAGE on failed run
    """
    signal.signal(signal.SIGINT, sigint_handler)

    args = parse_cli()

    if args.nocolor:
        Color.disable()

    # Need to configure terse first for proper output
    Settings.set("terse", args.terse)

    xprint("[+] sshady.py -- by Daniel Roberson @dmfroberson")
    xprint("")

    # Update setting for whether or not to attempt cracking of SSH keys
    Settings.set("crack", args.nocrack)

    # Make sure settings are sane
    if not Settings.update_wordlist(args.wordlist) or \
       not Settings.update_output_directory(args.outdir) or \
       not Settings.update_user_file(args.users) or \
       not Settings.update_host_file(args.hosts):
        return os.EX_USAGE

    # Search for users passwords.
    # TODO don't do this if key directory is specified.
    find_ssh_directories()

    # If a hostfile is specified, loop through hosts and try to login with
    # each of the harvested keys.
    if Settings.config("hostfile"):
        attempt_ssh_logins()

    xprint("")
    xprint("[+] You must defeat Sheng Long to stand a chance.")
    xprint("[+] Done.")

    return os.EX_OK