示例#1
0
    def parse(self, cmdline, silent=False):
        if len(cmdline) < 1:
            self._raise_error("No command supplied.")

        # Check if we can match the command portion
        pm = PrefixMatcher(self._getcmdnames())
        try:
            supplied_cmd = pm.matchunique(cmdline[0])
        except Exception as e:
            self._raise_error("Invalid command supplied: %s" % (str(e)))

        if supplied_cmd in self._aliases:
            supplied_cmd = self._aliases[supplied_cmd]

        command = self._commands[supplied_cmd]
        parser = FriendlyArgumentParser(prog=sys.argv[0] + " " + command.name,
                                        description=command.description,
                                        add_help=False)
        command.parsergenerator(parser)
        parser.add_argument("--help",
                            action="help",
                            help="Show this help page.")
        parser.setsilenterror(silent)
        args = parser.parse_args(cmdline[1:])
        return self.ParseResult(command, args)
示例#2
0
	def parse(self, cmdline, silent = False):
		if len(cmdline) < 1:
			self._raise_error("No command supplied.")

		# Check if we can match the command portion
		pm = PrefixMatcher(self._getcmdnames())
		try:
			supplied_cmd = pm.matchunique(cmdline[0])
		except Exception as e:
			self._raise_error("Invalid command supplied: %s" % (str(e)))

		if supplied_cmd in self._aliases:
			supplied_cmd = self._aliases[supplied_cmd]

		command = self._commands[supplied_cmd]
		parser = FriendlyArgumentParser(prog = sys.argv[0] + " " + command.name, description = command.description, add_help = False)
		command.parsergenerator(parser)
		parser.setsilenterror(silent)
		args = parser.parse_args(cmdline[1:])
		return self.ParseResult(command, args)
示例#3
0
#	airdroidclient is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with airdroidclient; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#	Johannes Bauer <*****@*****.**>

import sys
from AirdroidConnection import AirdroidConnection
from FriendlyArgumentParser import FriendlyArgumentParser

parser = FriendlyArgumentParser()
parser.add_argument("--port",
                    metavar="port",
                    type=int,
                    default=8888,
                    help="Port that Airdroid uses. Defaults to %(default)d.")
parser.add_argument(
    "-p",
    "--path",
    metavar="path",
    default="/sdcard/DCIM/Camera",
    help=
    "Path that is downloaded from the smart phone. Defaults to %(default)s.")
parser.add_argument(
    "-l",
    "--local",
        if len(self._args.nickname) == 0:
            identities = [airc.IRCIdentity(nickname="x" + os.urandom(4).hex())]
        else:
            identities = [
                airc.IRCIdentity(nickname=nickname)
                for nickname in self._args.nickname
            ]
        idgen = airc.ListIRCIdentityGenerator(identities)
        network = airc.IRCNetwork(irc_client_class=airc.client.RawIRCClient,
                                  irc_servers=irc_servers,
                                  identity_generator=idgen)
        task = network.task()
        await task


parser = FriendlyArgumentParser(description="Simple IRC client.")
parser.add_argument(
    "-H",
    "--hostname",
    metavar="hostname",
    default="irc.freenode.org",
    help="Specifies hostname to connect to. Defaults to %(default)s.")
parser.add_argument(
    "-p",
    "--port",
    metavar="port",
    type=int,
    default=6666,
    help="Specifies port to connect to. Defaults to %(default)d.")
parser.add_argument("-s",
                    "--use-tls",
示例#5
0
	@property
	def texpath(self):
		return self.datadir + "textures/"

	@property
	def tilesetfile(self):
		return self.datadir + "tileset/" + self._args.tileset + ".xml"

	@property
	def layoutfile(self):
		return self.datadir + "layout/" + self._args.game + "/" + self.layout + ".xml"

	def __getattr__(self, name):
		return getattr(self._args, name)

parser = FriendlyArgumentParser()
parser.add_argument("--datadir", metavar = "path", type = str, default = None, help = "Specifies directory in which the data files are located. Defaults to data/ relative to executable.")
parser.add_argument("-g", "--game", choices = [ "mahjong", "shisen" ], default = "mahjong", help = "Specifies which game to play")
parser.add_argument("-t", "--tileset", metavar = "name", default = "default", help = "Name of the tileset to use. Defaults to %(default)s")
parser.add_argument("-l", "--layout", metavar = "name", help = "Name of the board layout to use.")
parser.add_argument("-s", "--seed", metavar = "seed", type = int, help = "Seed of the game to use. Randomly chosen if omitted.")
parser.add_argument("--texresolution", metavar = "res", type = int, default = 512, help = "Specify texture resolution that should be used. Default is %(default)s.")
parser.add_argument("--allow-unsolvable", action = "store_true", default = False, help = "Allow non-solvable board layouts.")
args = parser.parse_args(sys.argv[1:])

config = Configuration(args)
layout = Layout(config.layoutfile)
tileset = TileSet(config.tilesetfile)
if args.game == "mahjong":
	board = MahjongBoard(layout.gridlen)
elif args.game == "shisen":
#!/usr/bin/python3
#	x509-cert-testcorpus - X.509 certificate test corpus
#	Copyright (C) 2019-2019 Johannes Bauer
#   License: CC-0

import sys
from CertDatabase import CertDatabase
from FriendlyArgumentParser import FriendlyArgumentParser

parser = FriendlyArgumentParser(
    description=
    "Search certificate database for a certificate which contains the proper data."
)
parser.add_argument(
    "-c",
    "--certdb",
    metavar="path",
    type=str,
    default="certs",
    help=
    "Specifies the path of the certificate database. Defaults to %(default)s.")
parser.add_argument("conn_id",
                    type=int,
                    help="Connection ID to dump certificates of")
args = parser.parse_args(sys.argv[1:])

certdb = CertDatabase(args.certdb)
connection = certdb.get_connection(args.conn_id)
CertDatabase.dump_connection(connection)
示例#7
0
    def _decode_uint16(self, offset):
        return self._decode_uint(offset, 2)

    def __len__(self):
        return len(self._data)

    def __repr__(self):
        if self.decoded_string is not None:
            show = self.decoded_string
        else:
            show = self.encoded_payload
        return "SubTitle(len=%d): %s" % (len(self), show)


parser = FriendlyArgumentParser()
parser.add_argument(
    "-r",
    "--render-string",
    type=str,
    default="%(gx).2f %(gy).2f %(gz).2f %(v_kmh).0f km/h",
    help=
    "printf-style format string according to which new subtitles shall be rendered. Defaults to \"%(default)s\". Valid rendering variables are gx, gy, gz, v_kmh."
)
parser.add_argument(
    "-v",
    "--verbose",
    action="count",
    default=0,
    help=
    "Be more verbose during conversion. Can be specified multiple times to increase verbosity."
#!/usr/bin/python3
#	x509-cert-testcorpus - X.509 certificate test corpus
#	Copyright (C) 2019-2019 Johannes Bauer
#   License: CC-0

import sys
from CertDatabase import CertDatabase
from FriendlyArgumentParser import FriendlyArgumentParser

parser = FriendlyArgumentParser(description = "Sanity check a certificate database.")
parser.add_argument("-s", "--stats-only", action = "store_true", help = "Only print stats, do not do any modification of the database.")
parser.add_argument("--skip-connection-check", action = "store_true", help = "Do not check if all connections have associated certificate data.")
parser.add_argument("--skip-unused-certificate-check", action = "store_true", help = "Do not check if there are dangling certificates that are not referenced in the TOC.")
parser.add_argument("--skip-optimization", action = "store_true", help = "Do not optimize databases as the last step.")
parser.add_argument("-c", "--certdb", metavar = "path", type = str, default = "certs", help = "Specifies the path of the certificate database. Defaults to %(default)s.")
args = parser.parse_args(sys.argv[1:])

certdb = CertDatabase(args.certdb)
(conn_count, cert_count) = (certdb.connection_count, certdb.certificate_count)
print("Analyzing database with %d connections and %d certificates." % (conn_count, cert_count))
if args.stats_only:
	sys.exit(0)

if not args.skip_connection_check:
	print("Checking for connections with missing certificates...")
	for (conn_number, connection) in enumerate(certdb.get_all_connections()):
		if (conn_number % 10000) == 0:
			print("Connection: %d / %d (%.1f%%)" % (conn_number, conn_count, conn_number / conn_count * 100))
		if any(cert is None for cert in connection.certs):
			print("Missing certificates for connection %d, removing connection." % (connection.conn_id))
			certdb.remove_connection(connection.conn_id)
示例#9
0
#   License: CC-0

import sys
import sqlite3
import contextlib
import subprocess
import multiprocessing
import hashlib
import time
import collections
import random
import re
from CertDatabase import CertDatabase
from FriendlyArgumentParser import FriendlyArgumentParser

parser = FriendlyArgumentParser(description = "Scrape certificates from websites.")
parser.add_argument("-d", "--domainname-dbfile", metavar = "filename", type = str, default = "certs/domainnames.sqlite3", help = "Specifies database file that contains the domain names to scrape. Defaults to %(default)s.")
parser.add_argument("-g", "--gracetime", metavar = "secs", type = float, default = 1, help = "Gracetime between scrapings of different domains, in seconds. Defaults to %(default).1f seconds.")
parser.add_argument("-p", "--parallel", metavar = "processes", type = int, default = 20, help = "Numer of concurrent processes that scrape. Defaults to %(default)d.")
parser.add_argument("-t", "--timeout", metavar = "secs", type = int, default = 15, help = "Timeout after which connection is discarded, in seconds. Defaults to %(default)d.")
parser.add_argument("-a", "--maxage", metavar = "days", type = int, default = 365, help = "Age after which another attempt is retried, in days. Defaults to %(default)d.")
parser.add_argument("-l", "--limit", metavar = "count", type = int, help = "Quit after this amount of calls.")
parser.add_argument("-c", "--certdb", metavar = "path", type = str, default = "certs", help = "Specifies the path of the certificate database. Defaults to %(default)s.")
parser.add_argument("--skip-local-db-update", action = "store_true", help = "Do not try to update the domainname database file from the actual certificate content database.")
parser.add_argument("domainname", nargs = "*", help = "When explicit domain names are supplied on the command line, only those are scraped and the max age is disregarded.")
args = parser.parse_args(sys.argv[1:])

class CertRetriever():
	_CERT_RE = re.compile("-----BEGIN CERTIFICATE-----[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----", flags = re.MULTILINE)

	def __init__(self, timeout):
示例#10
0
#!/usr/bin/python3
#
#

import sys
import geo
import cwrap
import gcwidget
from GCGTKApplication import GCGTKApplication
from GlutApplication import GlutApplication
from FriendlyArgumentParser import FriendlyArgumentParser

parser = FriendlyArgumentParser()
parser.add_argument("-r",
                    "--resolution",
                    metavar="height",
                    type=int,
                    default=720,
                    help="Resolution to display; defaults to %(default)d.")
parser.add_argument(
    "-m",
    "--mode",
    choices=["cairo", "gl", "png"],
    default="gl",
    help=
    "Type of rendering to use. Can be Cairo, OpenGL or PNG writing. Defaults to %(default)s."
)
parser.add_argument("-f",
                    "--fullscreen",
                    action="store_true",
                    help="Display in full screen mode.")
示例#11
0
    def compare(self):
        for (executed_insn_cnt, state1,
             state2) in self._trace1.align(self._trace2):
            self._compare_tracepoint(executed_insn_cnt, state1, state2)


def _names(text):
    if ":" not in text:
        raise argparse.ArgumentTypeError(
            "'%s' does not contain a ':' character" % (text))
    return text.split(":", maxsplit=1)


parser = FriendlyArgumentParser(
    description=
    "Compare two trace files; where they differ, show the instruction and deviation details."
)
parser.add_argument("-n",
                    "--name",
                    metavar="name1:name2",
                    type=_names,
                    help="Name of trace1 and trace2 separated by colon.")
parser.add_argument("trace1",
                    metavar="trace1_filename",
                    help="First trace for comparison")
parser.add_argument("trace2",
                    metavar="trace2_filename",
                    help="Second trace for comparison")
args = parser.parse_args(sys.argv[1:])

tc = TraceComparator(args)
示例#12
0
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with raptor-cheat; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#	Johannes Bauer <*****@*****.**>

import sys
import shutil
import struct
from FriendlyArgumentParser import FriendlyArgumentParser
from RaptorCrypto import RaptorCrypto

parser = FriendlyArgumentParser()
parser.add_argument("savegame",
                    metavar="savegame",
                    type=str,
                    help="Savegame file to edit.")
args = parser.parse_args(sys.argv[1:])

with open(args.savegame, "rb") as f:
    original_savegame = f.read()

savegame = bytearray(RaptorCrypto.decrypt(original_savegame))
#with open("decrypted.bin", "wb") as f:
#	f.write(savegame)

# Set money to a bunch
money_offset = 0x24
示例#13
0
			else:
				(result, details) = (TestResult.Skipped, None)
			print("%s: %s {%s}" % (name, result.name, details))

def proto_host_port(text):
	tokens = text.split(":")
	if len(tokens) not in [ 2, 3 ]:
		raise argparse.ArgumentTypeError("expected 2 or 3 arguments, but got %d" % (len(tokens)))
	if tokens[0] not in [ "smtp", "smtps" ]:
		raise argparse.ArgumentTypeError("protocol must be either smtp or smtps, you specified %s" % (tokens[0]))
	if len(tokens) == 2:
		tokens.append({
			"smtp":		"25",
			"smtps":	"465",
		}[tokens[0]])
	tokens[2] = int(tokens[2])
	return ServerAddress(*tokens)

parser = FriendlyArgumentParser()
parser.add_argument("-u", "--username", metavar = "user", help = "When testing also authenticated SMTP, this specifies the username to use.")
parser.add_argument("-P", "--passphrase-file", metavar = "filename", help = "When testing authenticated SMTP, this file contains the passphrase. If omitted, you are prompted on the command line.")
parser.add_argument("-V", "--valid-address", metavar = "mail_address", help = "Gives a valid mail address that the authenticated user is allowed to use.")
parser.add_argument("-i", "--valid-address-noauth", metavar = "mail_address", help = "Gives an address that is valid under control of the MTA under test, but that is not usable under the given account name.")
parser.add_argument("-r", "--relay-address", metavar = "mail_address", help = "Gives a valid relay address. DO NOT use a gmail/hotmail address for this since they might block your whole mailserver when its relaying settings are misconfigured. Use a service like trash-mail.com instead (i.e., that you can read but that won't blacklist your domain because of spoofy looking emails coming in).")
parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Increase verbosity. Can be specified multiple times.")
parser.add_argument("target", metavar = "proto:host[:port]", nargs = "+", type = proto_host_port, help = "Tuple of protocol, hostname and port of the mail server to test. Protocol can be either smtp or smtps. Port may be omitted and defaults to 25 for smtp or 465 for smtps.")
args = parser.parse_args(sys.argv[1:])

tester = MailTester(args)
tester.run()
示例#14
0
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with intapprox; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#	Johannes Bauer <*****@*****.**>

import sys
import math
from FriendlyArgumentParser import FriendlyArgumentParser, baseint

parser = FriendlyArgumentParser(
    description=
    "Approximate multiplication by a float value using integer arithmetic and system constraints."
)
parser.add_argument(
    "-b",
    "--bits",
    metavar="bits",
    type=int,
    default=32,
    help="Ensure that the topmost value never exceeds the register width.")
parser.add_argument("-m",
                    "--max-input-value",
                    metavar="int",
                    type=baseint,
                    required=True,
                    help="Maximum input value that is expected.")
parser.add_argument("-e",
    def reg15(self):
        # Exclude PC
        return "r%d" % (self._prng.randint(15))

    def reg16(self):
        return "r%d" % (self._prng.randint(16))

    def new_label(self, count=1):
        self._label += count
        return self.label()

    def label(self, number=0):
        return ".tclbl_%d" % (self._label - number)


parser = FriendlyArgumentParser()
parser.add_argument(
    "-s",
    "--seed",
    metavar="value",
    type=int,
    default=0,
    help=
    "Seed value to use for PRNG. Defaults to %(default)s. Different seed will generate different testcases."
)
parser.add_argument(
    "-l",
    "--length",
    metavar="count",
    type=int,
    default=1000,
示例#16
0
	def __init__(self):
		self._parser = FriendlyArgumentParser(prog = sys.argv[0], description = "Tool to communicate with Gamma Scout geiger counters and read out the radiation log", add_help = False)
		self._parser.add_argument("-d", "--device", metavar = "device", type = str, default = "/dev/ttyUSB0", help = "Specifies the device that the Gamma Scout is connected to. For debugging purposes, 'sim' may be specified to include simulation sources. Default is %(default)s")
		self._parser.add_argument("-p", "--protocol", metavar = "version", type = str, choices = [ "v1", "v2" ], default = "v2", help = "Specifies the device protocol the connected Gamma Scout uses. Older models use v1 while newer versions use v2. Possible options are %(choices)s, default is %(default)s")
		self._parser.add_argument("--simulate", action = "store_true", help = "Do not connect to a real Gamma Scout device, but connect to a simulator (device name should be UNIX socket)")
		self._parser.add_argument("--force", action = "store_true", help = "Allow execution of commands that are not usually needed by the user (you should only use this if you know what you're doing)")
		self._parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Show mode logging info. May be specified multiple times to increasse verbosity")
		self._parser.add_argument("--help", action = "store_true", help = "Show this help page and exit")
		self._parser.add_argument("--localstrftime", action = "store_true", help = "For replacement format string, use local time instead of UTC. By default, UTC is chosen.")
		self._parser.add_argument("--noheader", action = "store_true", help = "When printing data in a textual representation, omit the headline")
		self._parser.add_argument("--nologcache", action = "store_true", help = "When executing the readlog command multiple times, read out the log every single time (default is to cache subsequent calls to readlog)")
		self._parser.add_argument("--nodevice", action = "store_true", help = "Do not connect to a Gamma Scout device or to a simulator instance, but just perform offline commands (like log conversion)")
		self._parser.add_argument("--line-buffered", action = "store_true", help = "Flush the output buffers of files after every line. Useful if you are connecting GammaScoutUtil to a pipe and want to directly process the values")
		self._parser.add_argument("--timeout-factor", metavar = "factor", type = float, default = 1.0, help = "Multiply all timeout values with a specific coefficient. Can be used if the Gamma Scout frequently times out. Default is %(default).1f")
		self._parser.add_argument("--txt-format", metavar = "fmtstr", type = str, help = "Sets the output string for the txt output backend. Named printf arguments must be used; recognized names are %s" % (", ".join(OutputBackends.OutputBackendTXT.get_known_args())))
		self._parser.add_argument("--gstool-txt-format", action = "store_true", help = "Shortcut for --txt-format which sets the output format string that gstool uses")
		self._parser.add_argument("--date-format", metavar = "fmtstr", type = str, default = "%Y-%m-%d %H:%M:%S", help = "Sets the strftime format string for the txt and csv output backends. Default is %(default)s")
		self._parser.add_argument("commands", metavar = "command", type = str, nargs = "+", help = "Commands that are processed by the Gamma Scout util, in order of occurence")
		self._commands = [
			ArgDefinition(name = "identify", help = "Displays information like the Gamma Scout software version and serial number of the device"),
			ArgDefinition(name = "devidentify", help = "Output extended information about the Gamma Scout for development purposes"),
			ArgDefinition(name = "synctime", help = "Synchronizes the time with the current local system time (not recommended)"),
			ArgDefinition(name = "syncutctime", help = "Synchronizes the time with the current time in UTC (GMT+0), preferred way of syncing the Gamma Scout time"),
			ArgDefinition(name = "settime", args = [ "YYYY-MM-DD-HH-MM-SS" ], help = "Sets the time to the user defined value"),
		 	ArgDefinition(name = "readlog", args = [ "[txt|sqlite|csv|xml|bin|sql]", "[Filename/Connstr]" ], help = "Reads out Gamma Scout log in text format, SQLite3 format, CSV, XML or binary format and writes the results to the specified filename; only binary data can later on be imported back using the 'readbinlog' command"),
		 	ArgDefinition(name = "readbinlog", args = [ "[Infile]", "[txt|sqlite|csv|xml|bin]", "[Outfile]" ], help = "Reads a Gamma Scout log from a previously written binary file"),
			ArgDefinition(name = "clearlog", help = "Deletes the Gamma Scout log"),
			ArgDefinition(name = "readcfg", args = [ "[Filename]" ], help = "Reads out the configuration blob and writes it in the specified file in binary format"),
			ArgDefinition(name = "devicereset", help = "Completely resets the device to its factory defaults. Do not perform this operation unless you have a good reason to. Requires the --force option to be set in order to work"),
			ArgDefinition(name = "online", args = [ "[Intervaltime]", "[txt|csv|sql]", "[Filename/Connstr]" ], help = "Switches the Gamma Scout into online-mode and records the values it receives continuously into the given file in the specified syntax (every n seconds). Valid intervals are " + GSOnline.possible_interval_str() + " seconds"),
			ArgDefinition(name = "switchmode", args = [ "[standard|pc|online]" ], help = "Switches the Gamma Scout into the desired mode and then exits (leaving it in that mode)"),
		]
		self._knowncommands = { cmd.name: cmd for cmd in self._commands }

		orig_printhelp = self._parser.print_help
		def printhelp(*args, **kwargs):
			orig_printhelp(*args, **kwargs)
			print(file = sys.stderr)
			print("commands:", file = sys.stderr)
			for cmd in self._commands:
				if len(cmd.args) == 0:
					print("  %s" % (cmd.name), file = sys.stderr)
				else:
					print("  %s:%s" % (cmd.name, ":".join(cmd.args)), file = sys.stderr)
				for line in textwrap.wrap(cmd.help, initial_indent = "    ", subsequent_indent = "    "):
					print(line, file = sys.stderr)
			print(file = sys.stderr)
			print("examples:", file = sys.stderr)
			print("  Identify a Gamma Scout v1 at /dev/ttyS0:", file = sys.stderr)
			print("    %s -p v1 -d /dev/ttyS0 identify" % (sys.argv[0]), file = sys.stderr)
			print("  Identify a Gamma Scout v2 at /dev/ttyUSB3:", file = sys.stderr)
			print("    %s -d /dev/ttyUSB3 identify" % (sys.argv[0]), file = sys.stderr)
			print("  Read out Gamma Scout log into SQLite database, clear log and sync UTC time:", file = sys.stderr)
			print("    %s readlog:sqlite:/home/joe/gslog.sqlite clearlog syncutctime" % (sys.argv[0]), file = sys.stderr)
			print("  Connect to simulator and read out log of simulator:", file = sys.stderr)
			print("    %s -d simsocket --simulate readlog:csv:outfile.csv" % (sys.argv[0]), file = sys.stderr)
			print("  Read in binary blob log and write into database without any device:", file = sys.stderr)
			print("    %s --nodevice readbinlog:v2log.bin:sqlite:database.sqlite" % (sys.argv[0]), file = sys.stderr)
			print("  Read in v1 binary blob log and print it on standard output:", file = sys.stderr)
			print("    %s --nodevice -p v1 readbinlog:v1log.bin:txt:-" % (sys.argv[0]), file = sys.stderr)
			print("  Read Gamma Scout log into file that is named after current date and time:", file = sys.stderr)
			print("    %s readlog:txt:%%Y/%%m/%%Y-%%m-%%d-%%H-%%M-%%S.txt" % (sys.argv[0]), file = sys.stderr)
			print("  Read out log, write it to binary file and to database and clear log of Gamma Scout afterwards:", file = sys.stderr)
			print("    %s readlog:bin:%%Y/%%m/%%Y-%%m-%%d-%%H-%%M-%%S.txt readlog:sqlite:database.sqlite clearlog" % (sys.argv[0]), file = sys.stderr)
			print()
			print("notes:", file = sys.stderr)
			notes = [
				"for the txt, csv and xml output backends, '-' may be speficied as filename which will cause the output to be printed on stdout",
				"filenames support strftime substitutions",
				"if filename specification contain subdirectories, they will be created if they do not exist",
				"the 'sql' output backend does not take a filename, but a connection string in the form key1=value1,key2=value2,... and so on. Recognized keys are dbdialect, dbname, tablename, file",
			]
			for note in notes:
				for line in textwrap.wrap(note, initial_indent = "  - ", subsequent_indent = "    "):
					print(line, file = sys.stderr)
			print()
			print("version: %s" % (Globals.VERSION))
		self._parser.print_help = printhelp

		self._parsedcmds = [ ]
#!/usr/bin/python3
#	x509-cert-testcorpus - X.509 certificate test corpus
#	Copyright (C) 2019-2020 Johannes Bauer
#   License: CC-0

import sys
import subprocess
import glob
import re
import hashlib
from CertDatabase import CertDatabase
from FriendlyArgumentParser import FriendlyArgumentParser

parser = FriendlyArgumentParser(
    description=
    "Search certificate database for a certificate which contains the proper data."
)
parser.add_argument(
    "-c",
    "--certdb",
    metavar="path",
    type=str,
    default="certs",
    help=
    "Specifies the path of the certificate database. Defaults to %(default)s.")
parser.add_argument("-n",
                    "--nth-match",
                    metavar="no",
                    type=int,
                    default=1,
                    help="Show the n-th match. Defaults to the first match.")
示例#18
0
                            with open(self._args.outfile, "w") as f:
                                json.dump(cbc.replies, f)
                            print(cbc.replies)
                await asyncio.sleep(1)

        async def show_state():
            while True:
                if network.client is not None:
                    print(network.client.channels)
                await asyncio.sleep(1)

        await asyncio.gather(list_channels_join_most_popular(), query_users(),
                             show_state())


parser = FriendlyArgumentParser(
    description="Simple IRC client that sends CTCP queries to clients.")
parser.add_argument(
    "--delay-between-msgs",
    metavar="secs",
    type=int,
    default=60,
    help=
    "Delay between sending out CTCP messages, in seconds. Defaults to %(default)d."
)
parser.add_argument("--ctcp-message",
                    metavar="name",
                    default="VERSION",
                    help="CTCP message to send. Defaults to %(default)s.")
parser.add_argument(
    "-c",
    "--channel",
示例#19
0
                                    "mode":
                                    self._args.mode,
                                })
            self._jobserver.add(job)

    def run(self):
        while True:
            result = input("Ready to scan next batch (q to quit)...")
            result = result.strip()
            if result == "q":
                break
            self.scan_next_batch()
        self._jobserver.shutdown()


parser = FriendlyArgumentParser()
parser.add_argument(
    "-c",
    "--config-file",
    metavar="filename",
    type=str,
    default="config.json",
    help="Configuration file to read. Defaults to %(default)s.")
parser.add_argument(
    "-o",
    "--outdir",
    metavar="dirname",
    type=str,
    default="output/",
    help="Output directory to place files in. Defaults to %(default)s.")
parser.add_argument(
示例#20
0
#	Johannes Bauer <*****@*****.**>
#

import os
import sys
import time
import subprocess
import tempfile
import socket
from FriendlyArgumentParser import FriendlyArgumentParser, baseint
from DebuggingProtocol import ARMDebuggingProtocol
from TraceWriter import TraceWriter, TraceRegisterSet, TraceMemory
from TraceReader import TraceReader

parser = FriendlyArgumentParser(
    description=
    "Execute a binary either in libthumb2sim or in qemu and write a JSON trace file."
)
parser.add_argument(
    "--rom-base",
    metavar="address",
    type=baseint,
    default=0,
    help=
    "ROM base address, defaults to 0x%(default)x bytes. Only relevant when a binary is specified as input file."
)
parser.add_argument(
    "--ram-base",
    metavar="address",
    type=baseint,
    default=0x20000000,
    help=
示例#21
0
#!/usr/bin/python3
#	x509-cert-testcorpus - X.509 certificate test corpus
#	Copyright (C) 2018-2018 Johannes Bauer
#   License: CC-0

import sys
import sqlite3
import contextlib
import csv
from FriendlyArgumentParser import FriendlyArgumentParser

parser = FriendlyArgumentParser(
    description=
    "Import domain names from CSV lists and already scraped certificates.")
parser.add_argument(
    "-d",
    "--domainname-dbfile",
    metavar="filename",
    type=str,
    default="certs/domainnames.sqlite3",
    help=
    "Specifies database file that contains the domain names to scrape. Defaults to %(default)s."
)
parser.add_argument(
    "--reset",
    action="store_true",
    help=
    "Clear the domain name information and rely solely on the information found in the database."
)
parser.add_argument("csvfiles",
                    nargs="*",
示例#22
0
#
#	You should have received a copy of the GNU General Public License
#	along with libthumb2sim; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#	Johannes Bauer <*****@*****.**>
#

import sys
import os
import subprocess
import shutil
import contextlib
from FriendlyArgumentParser import FriendlyArgumentParser

parser = FriendlyArgumentParser()
parser.add_argument("-m",
                    "--minify-tracefiles",
                    action="store_true",
                    help="Minify all generated tracefiles")
parser.add_argument("tc_dir",
                    metavar="tc_dir",
                    type=str,
                    help="Testcase template directory for input data")
parser.add_argument("trace_dir",
                    metavar="trace_dir",
                    type=str,
                    help="Trace output directory")
args = parser.parse_args(sys.argv[1:])

subprocess.check_call(["make", "clean"])
示例#23
0
    def y(self):
        assert (self._cmd in ["setpixel", "clrpixel"])
        return self._args[1]

    @property
    def width(self):
        assert (self._cmd in ["setwidth"])
        return self._args[0]

    @property
    def threshold(self):
        assert (self._cmd in ["threshold"])
        return self._args[0]


parser = FriendlyArgumentParser()
parser.add_argument(
    "-t",
    "--threshold",
    metavar="value",
    type=parse_threshold,
    default=0x60,
    help=
    "Threshold at which pixels will be considered set. Defaults to %(default)d, must be a value between 1 and 255."
)
parser.add_argument(
    "-c",
    "--charset",
    metavar="chars",
    type=str,
    help=
示例#24
0
		cur = self.start
		while cur <= self.end:
			yield cur
			cur = cur + datetime.timedelta(1)

	def __str__(self):
		if self.start == self.end:
			return "Period<%s>" % (self.start)
		else:
			return "Period<%s - %s>" % (self.start, self.end)


def isodate(text):
	return datetime.datetime.strptime(text, "%Y-%m-%d").date()

parser = FriendlyArgumentParser()
parser.add_argument("-e", "--eligibility", metavar = "period", type = str, help = "Eligibility period. Show the period with the current year's name by default.")
parser.add_argument("-n", "--no-merge", action = "store_true", help = "Do not merge subsequent vacation days into one block.")
parser.add_argument("-t", "--to-day", metavar = "date", type = isodate, help = "Only consider period until the given date. Needs to be ISO format, i.e., yyyy-mm-dd.")
parser.add_argument("infile", metavar = "json", type = str, help = "Input file to parse.")
args = parser.parse_args(sys.argv[1:])

with open(args.infile) as f:
	data = json.load(f)

eligibility = args.eligibility or datetime.datetime.now().strftime("%Y")
if eligibility not in data.get("eligibility", { }):
	raise KeyError("Input file has no 'eligibility' section or eligibility section has no '%s' key." % (eligibility))
eligibility = data["eligibility"][eligibility]

# Get the full period first
示例#25
0
    def run(self):
        while True:
            self._iteration_regulate()
            time.sleep(self._args.regulation_interval)

    def reset(self):
        # Reset automatic temperature determination
        subprocess.check_call([
            "nvidia-settings", "--assign",
            "[%s]/GPUFanControlState=0" % (self._args.gpu)
        ],
                              stdout=subprocess.DEVNULL,
                              stderr=subprocess.DEVNULL)


parser = FriendlyArgumentParser()
parser.add_argument(
    "-t",
    "--target-temp",
    metavar="temp",
    type=float,
    default=55,
    help=
    "Specifies the GPU target temperature in °C. Defaults to %(default).0f°C")
parser.add_argument(
    "-i",
    "--regulation-interval",
    metavar="secs",
    type=float,
    default=2.5,
    help=