Пример #1
0
def main():
    opt = op("Usage: %prog [arg] [value]")
    opt.add_option("-f",
                   "--file",
                   dest="file",
                   default="encodeme.txt",
                   help="Set the name of the file",
                   type="string")
    opt.add_option("-k",
                   "--key",
                   dest="key",
                   default=8,
                   help="Set key",
                   type="int")
    opt.add_option("-o",
                   "--out",
                   dest="out",
                   default="newfile.txt",
                   help="Set output's file name",
                   type="string")
    opt.add_option(
        "-d",
        "--do",
        dest="do",
        default="e",
        help="Just give a random value tu decode, if not it is going to encode."
    )
    (o, argv) = opt.parse_args()
    check = encodefile(o.file, o.key, o.out, o.do)
    if check:
        print("Well done, output file in {}".format(o.out))
    else:
        print("There was an execution exception...")
Пример #2
0
def main():
    opt = op("Usage: %prog [args] [values]")
    opt.add_option("-s",
                   "--server",
                   dest="server",
                   help="Set server's ip",
                   default="127.0.0.1")
    opt.add_option("-p",
                   "--port",
                   dest="port",
                   help="Set server's port",
                   default=5000,
                   type="int")
    opt.add_option("-k",
                   "--key",
                   dest="key",
                   help="Set key",
                   default="YxqChramWzhDUQiNoAnNseAYTblCjapnL8aQu3ehofQ=")
    (o, argv) = opt.parse_args()
    o.key = o.key.encode()
    c = Client()
    c.start(o.server, o.port, o.key)
    h = Thread(target=c.hear)
    h.daemon = True
    h.start()
    if pv()[0] == "3":
        raw_input = input
    cmd = ""
    while cmd != "exit":
        cmd = raw_input(">>>")
        c.send(cmd)
def main():
    opt = op("Usage: %prog [args] [values]")
    opt.add_option("-k",
                   "--key",
                   dest="key",
                   help="Set key.",
                   default=4,
                   type="int")
    opt.add_option(
        "-d",
        "--do",
        dest="do",
        help=
        "If this argument is equal to its default value ('encode') it will encode your text, else, it will decode it.",
        default="encode")
    (o, argv) = opt.parse_args()
    if pv()[0] == "3":
        raw_input = input
    mytext = raw_input("Input your text here: ")
    if o.do == "encode":
        encoded = encode(mytext, o.key)
    else:
        encoded = decode(mytext, o.key)
    print(encoded)
    pyperclip.copy(encoded)
Пример #4
0
def main():
    opt = op("Usage: %prog [args] [values]")
    opt.add_option("-k",
                   "--key",
                   dest="key",
                   help="Set key",
                   default="CXNQWSUJLYBOZAPRHIMGDVTFEK")
    opt.add_option(
        "-i",
        "--input",
        dest="input",
        help=
        "Set if you are going to input the message manually ir not. [input, variable]",
        default="manually")
    opt.add_option(
        "-d",
        "--do",
        dest="do",
        help=
        "Set what the programm is going to do [decode, encode, generatekey]",
        default="encode")
    (o, args) = opt.parse_args()
    message = checkargs(o.key, o.do, o.input)
    if o.do != "generatekey":
        translated = sub(message, o.key, o.do)
        print(
            "The {}ed message is:\n {}\nThe message was copy in the clipboard."
            .format(o.do, translated))
        copy(translated)
    else:
        newkey = getkey()
        print("New key: {}\nThe key was copy in the clipboard".format(newkey))
        copy(newkey)
Пример #5
0
def main():
	oP = op("Usage: %prog [flags] [args]");
	oP.add_option("-H", "--host", dest="ip",type="str", default="127.0.0.1", help="Set master's ip.");
	oP.add_option("-p","--port",dest="port",  type="int", default=5000, help="Set master's port");
	oP.add_option("-k","--key", type="str", dest="key", default="eajlkwbcpqynvhigdrzotusfmx", help="Set cryptography key");
	(o, argv) = oP.parse_args();
	p = Prey(o.ip, o.port, o.key);
Пример #6
0
def main():
	opt = op("Usage: %prog [args] [values]")
	opt.add_option("-k", "--key",dest="key",help="Set the key.",default="PIZZA")
	opt.add_option("-m", "--mode", dest="do", help="Set what the program is going to do [encode, decode, onepad].",default="encode")
	opt.add_option("-i", "--input", dest="input", help="Set how the data is going to be input [variable, typed].",default="typed")
	(o, argv) = opt.parse_args()
	o.key = o.key.upper()
	message = checkargs(o.do, o.input, o.key)
	if o.do == "onepad":
		translated = onepad(message)
	else:
		translated = translate(message, o.key, o.do)
	print("{}ed message:\n{}\nTranslated message copied in the clipboard.".format(o.do,translated))
	copy(translated)
Пример #7
0
def main():
    opt = op("Usage: %prog [arg] [value]")
    opt.add_option("-H",
                   "--host",
                   dest="host",
                   default="127.0.0.1",
                   help="Set server's ip")
    opt.add_option("-p",
                   "--port",
                   dest="port",
                   default=5000,
                   help="Set server's port",
                   type="int")
    opt.add_option("-k",
                   "--key",
                   dest="key",
                   default="YxqChramWzhDUQiNoAnNseAYTblCjapnL8aQu3ehofQ=",
                   help="Set key",
                   type="string")
    opt.add_option(
        "-l",
        "--listen",
        dest="l",
        default=2,
        help="Set how many clients can be connected at the same time",
        type="int")
    (o, argv) = opt.parse_args()
    o.key = o.key.encode()
    s = Server()
    s.start(o.host, o.port, o.key, o.l)
    w = Thread(target=s.wait4all)
    w.daemon = True
    w.start()
    h = Thread(target=s.hear2all)
    h.daemon = True
    h.start()
    if pv()[0] == "3":
        raw_input = input
    if p()[0] == "W":
        clear = "cls"
    else:
        clear = "clear"
    costumclear = clear
    cmd = ""
    while cmd != "exit":
        cmd = raw_input(">>>")
        if cmd == costumclear:
            system(clear)
Пример #8
0
def main():
    oP = op("Usage: %prog [flags] [args]")
    oP.add_option("-H",
                  "--host",
                  dest="ip",
                  default="127.0.0.1",
                  type="str",
                  help="Set your host")
    oP.add_option("-p",
                  "--port",
                  dest="port",
                  default=5000,
                  type="int",
                  help="Set your port")
    oP.add_option("-k",
                  "--key",
                  dest="key",
                  default="eajlkwbcpqynvhigdrzotusfmx",
                  type="str",
                  help="Set key")
    (o, argv) = oP.parse_args()
    c = Coyote(o.ip, o.port, o.key)
    c.shell()
Пример #9
0
        try:
            in_idxs.append(pkl.load(f))
            out_idxs.append(pkl.load(f))
        except EOFError:
            break

    f.close()

    return (in_idxs, out_idxs)


if __name__ == '__main__':
    # Parse the arguments
    usage = ('usage: %prog [options]'
             ' <parameter_file_name> <ins_and_outs_file_name>')
    pars = op(usage=usage)
    pars.add_option(
        '-k',
        '--k_percent',
        dest='k_percent',
        help='Percent k of top weights to extract.',
        metavar='K',
        default=0.1
    )
    pars.add_option(
        '-w',
        '--top_weights',
        help='Whether to identify neurons based on largest set of weights.',
        action='store_true',
        default=False
    )
Пример #10
0
		self.command = command
	def run(self, shell=True):
		import subprocess as sp
		process = sp.Popen(self.command, shell = shell, stdout = sp.PIPE, stderr = sp.PIPE)
		self.pid = process.pid
		self.output,self.error = process.communicate()
		self.failed = process.returncode
		return self
	
	@property
	
	def returncode(self):
		return self.failed

# ------------------------ Parse command line options and arguments ------------------------
parser = op()
parser.add_option('-c', '--colors', action='store', default='orange,red', help='Supply either one or more colors in comma separated values. Example: orange,red,blue')
parser.add_option('-n', '--number-of-updates', action='store', default=10, type='int', help='The number of maximum updates to display in Conky.')
parser.add_option('-g', '--get-number', action='store_true', default=False, help='Returns the number of updates available through pacman.')
parser.add_option('-e', '--header', action='store', default='', help='Sets a header for your conky output. Replacable variables are $n for number of updates.')
(options, args) = parser.parse_args()

# --------------------------------------------- The -g flag ------------------------------------------------

theupdates = Command("pacman -Qu").run()
theupdates_ord = theupdates.output
theupdates_ord = theupdates_ord.decode('ascii')
theupdates = theupdates_ord.split("\n") # Split output of -Qu by line
numdates = len(theupdates) # Count the lines
if numdates > 0: # if there are actually updates
	try:
      self._vocab = file(vocabfile).read().split()
      if normalize:
         self._vecs = ugly_normalize(self._vecs)
      self._w2v = {w:i for i,w in enumerate(self._vocab)}

   @classmethod
   def load(cls, vecsfile, vocabfile=None):
      return Embeddings(vecsfile, vocabfile)

   def word2vec(self, w):
      return self._vecs[self._w2v[w]]


if __name__=='__main__':
    usage="usage: %prog [options]" 
    parser=op(usage=usage)
    parser.add_option('--vec','--vec_file',type='string',\
                        dest='vec_file',help='词向量文件_npy')
    parser.add_option('--vocab','--vocab_file',type='string',\
                        dest='vocab_file',help='词典文件_vocab') 
    parser.add_option('--train','--train_file',type='string',\
                        dest='train_file',help='训练文件')    
    parser.add_option('--test','--test_file',type='string',\
                        dest='test_file',help='测试文件')
    parser.add_option('--output','--output_file',type='string',\
                        dest='output_file',help='测试文件')
#    parser.add_option('--len','--sen_len',type='int',default=3,\
#                        dest='sen_len',help='句子长度')  
    
    
    (options, args) = parser.parse_args()
Пример #12
0
from hashlib import md5
from sys import argv
from optparse import OptionParser as op

if __name__ == '__main__':
    parser = op("Usage: %prog [argument] [value]")
    parser.add_option("-H",
                      "--hash",
                      type="string",
                      help="Set the md5 hash.",
                      dest="hash")
    parser.add_option("-d",
                      "--dictionary",
                      type="string",
                      help="set password dictionary.",
                      dest="dic")
    (opt, argv[1:]) = parser.parse_args()
    try:
        with open(opt.dic, "r") as d:
            for line in d.readlines():
                line = line.strip()
                rt = md5(line.encode()).hexdigest()
                if rt == opt.hash:
                    print("{} is {}".format(opt.hash, line))
                    break
    except Exception as e:
        print(e)
Пример #13
0
def main():
    '''
    Our main application
    '''

    parser = op("usage ipblisted.py --ip [ip]")
    parser.add_option('--proxy', action="store", dest="proxy", help="Useful for when behind a proxy")
    parser.add_option('--proxy_user', action="store", dest="proxy_user")
    parser.add_option('--proxy_pass', action="store", dest="proxy_pass")
    parser.add_option('--good', default=False, action="store_true", dest="show_good", help="Displays lists that the IP did NOT show up on.")
    parser.add_option('--skip-dnsbl', default=False, action="store_true", dest="skip_dnsbl", help="Skips the checking DNS Blacklists")
    parser.add_option('--skip-bl', default=False, action="store_true", dest="skip_bl", help="Skips the checking of text based blacklists")
    parser.add_option('--no-cache', default=False, action="store_true", dest="no_cache", help="This will prevent caching of text based blacklists")
    parser.add_option('--clear-cache', default=False, action="store_true", dest="clear_cache", help="This will clear the existing cache")
    parser.add_option('--cache-timeout', default=60*60*12, action="store", dest="cache_timeout", help="Number of seconds before cache results are to expire (Default: 12 hours)")
    parser.add_option('--threads', default=5, action="store", dest="threads", help="Sets the number of feed search threads")
    parser.add_option('--infile', default=None, action="store", dest="infile", help="A newline separated list of IP addresses")
    parser.add_option('--ip', action="store", dest="ip")
    parser.add_option('-w','--wan', action="store_true", dest="wan", default=False, help="Will add your WAN ip to the list of IP addresses being checked.")
    parser.add_option('-f', '--format', action="store", dest="format", help="Set the output format for an outfile", default="csv")
    parser.add_option('-o', '--outfile', action="store", dest="outfile", help="Where to write the results", default=None)
    (options, args) = parser.parse_args()

    if options.format:
        allowed_formats = ['csv', 'xls', 'xlsx', 'txt']
        if not options.format in allowed_formats:
            cprint("[!] Invalid format \"{}\".  Please select a valid format {}".format(options.format, ', '.join(allowed_formats)), RED)
            sys.exit(1)

    if options.outfile:
        print("[*] Results will be saved to {} in {} format".format(options.outfile, options.format))

    # Check if the user supplied an IP address or IP block
    if options.ip is None and options.infile is None and options.wan is False:
        print("[!] You must supply an IP address, the WAN flag or a file containing IP addresses.")
        sys.exit(1)

    # Set our list of IPs to an empty list
    ips = []

    # Load up the IP in the --ip flag
    if options.ip:
        if '\\' in options.ip or '/' in options.ip:
            cprint("[!] Detected CIDR notation, adding all IP addresses in this range", BLUE)
            for ip in IPSet([options.ip]):
                ips += [str(ip)]
        elif len(options.ip.split(',')) > 0:
            ips += [ip for ip in options.ip.split(',') if ip != '']  # Handles when user does ,%20 
        else:
            ips += [options.ip]

    # If the user supplied a file load these as well
    if options.infile:
        ips += [ip for ip in file(options.infile).read().split('\n') if ip != '']

    if options.wan:
        ip = wan_ip()
        if ip:
            ips += [ip]
        else:
            cprint("[!] There was an issue trying to gather the WAN IP address.", RED)

    # Check if the user set their credentials when using a proxy
    if options.proxy:
        if options.proxy_user is None or options.proxy_pass is None:
            cprint("[!] Warning, no proxy credentials supplied.  Authenticated proxies may not work.", BLUE)
        else:
            options.proxy_pass = urllib.quote(options.proxy_pass)

    # Initialize a queue for the feeds to go in
    fq = Queue()

    # Load in all the feeds from the feed configuration file
    feeds = load_feeds({"skip_bl": options.skip_bl, "skip_dnsbl": options.skip_dnsbl})

    # Establish the requests cache
    if not options.no_cache:
        requests_cache.install_cache('ipblisted', expire_after=int(options.cache_timeout))

        # If the user wants to manually clear the cache, do it now
        if options.clear_cache:
            requests_cache.clear()

    # If there are no feeds set, just exit the program
    if len(feeds) == 0:
        cprint("[!] No feeds were defined, please define them in feeds.json or don't skip them all.", RED)
        sys.exit(1)

    # Final check to make sure we actually have a list of IP addresses to check
    if len(ips) == 0:
        cprint("[!] No IP addresses were listed to check.  Please check your syntax and try again.", RED)

    feed_results = []

    # Loop through each IP and find it
    print("[*] Checking {} IP addresses against {} lists".format(len(ips), len(feeds)))
    for ip in ips:

        print("[*] Searching Blacklist feeds for IP {ip}".format(ip=ip))

        # Build the feed requests queue
        oq = Queue()

        # Create a queue of all the feeds we want to check
        [fq.put(f) for f in feeds]
	qsize = fq.qsize()

        # Start up our threads and start checking the feeds
	threads = [FeedThread(ip, options, fq, oq) for i in range(0,options.threads)]
        [t.start() for t in threads]
        [t.join() for t in threads]

        # Set the number of lists we have found to 0
        find_count = 0

        # Go through each feed and see if we find the IP or block
        results = [r for r in oq.queue]

        if options.outfile:
            convert_results(results, ip, options.outfile)

        # Print out if the IP was found in any of the feeds
        for result in results:

            output = "[*] {name}: {found}".format(**result)

            if result["found"] == "Found":
                find_count += 1
                cprint(output,RED)
                continue

            if options.show_good:
                cprint(output)

        if find_count == 0:
            cprint("[*] Not found on any defined lists.", GREEN)
        else:
            cprint("[*] Found on {}/{} lists.".format(find_count,qsize), RED)
        print("[-]")
Пример #14
0
Файл: kB.py Проект: berjc/kb
def init_parser():
  parser = op()
  parser.add_option('-i', '--input', dest='audio_dir', help='use audio pieces in SRC_DIRECTORY', metavar='SRC_DIRECTORY')
  parser.add_option('-s', '--seed', dest='seed', help='starts track list with SEED', metavar='SEED')
  return parser.parse_args()
Пример #15
0
            filelist.append(file)
        else:
            continue


def parse(l):
    with open(l, "r") as h:
        hashes = h.readlines()
    for file in filelist:
        with open(file, "rb") as f:
            if md5(f.read()).hexdigest() in hashes:
                print("**{}'s hash in {}".format(file, l))


if __name__ == '__main__':
    ops = op("USAGE: %prog [args] [values]")
    ops.add_option("-l",
                   "--list",
                   dest="list",
                   default="list.txt",
                   help="Set malware's hashes list.",
                   type="string")
    ops.add_option("-f",
                   "--file",
                   dest="file",
                   default="all in this dir",
                   help="Set what file(s) is(are) going to be check.",
                   type="string")
    (o, argv) = ops.parse_args()
    filelist = []
    if o.file == "all in this dir":
Пример #16
0
from optparse import OptionParser as op
from utils.base import Agent, Plugin
from multiprocessing import Process, Queue
from utils.elasticsearch import Elastic
from dotenv import load_dotenv
from utils.ldap import LDAPSource

logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

if __name__ == "__main__":

    load_dotenv(dotenv_path="config.txt")
    load_dotenv()

    parser = op(description='Reflex Worker Agent')
    parser.add_option(
        '--name',
        dest='name',
        type=str,
        action="store",
        help=
        'A friendly name to call this agent.  Overrides the default system name.'
    )
    parser.add_option('--pair', dest='pair', action='store_true')
    parser.add_option('--token',
                      dest='token',
                      type=str,
                      action="store",
                      help='Token used to pair the agent with the console')
    parser.add_option('--console',
Пример #17
0
def main():
    proxy = None
    monitor = None
    ips_worker = []
    ips = []
    roles = []
    hosts = []
    dev = []
    record = recorder()
    Y = yum()
    usage = "usage: %prog options"
    option = op(usage)
    option.add_option("-f",
                      "--file",
                      default=False,
                      action="store",
                      dest="filename",
                      help="point the config file",
                      metavar="FILE")
    option.add_option("-i",
                      "--ips",
                      default=False,
                      action="store",
                      dest="ips",
                      help="point the ips except file",
                      metavar="Ips")
    (options, arg) = option.parse_args()
    if not options.filename and not options.ips:
        option.print_help()
        return
    if options.filename != False:
        if not os.path.exists(options.filename):
            print "ERROR : [ main ] config file is not existed."
            return
        reader = open(options.filename)
        configs = reader.readlines()
        reader.close()
        for config in configs:
            temp = config.split(":")
            if temp[0] == "proxy" or temp[0] == "worker" or temp[
                    0] == "monitor":
                roles.append(temp[0].strip())
                ips.append(temp[1].strip())
            elif temp[0] == "proxyhost" or temp[0] == "workerhost" or temp[
                    0] == "monitorhost":
                hosts.append(temp[1].split("\n")[0])
            elif temp[0] == "device":
                dev.append(temp[1])
            else:
                raise Exception("config file is wrong,please check it.")
    else:
        ips = options.ips.split(",")
        for i in range(len(ips)):
            if i == 0:
                roles.append("proxy")
            else:
                roles.append("worker")
    for i in range(len(ips)):
        if roles[i] == "proxy":
            proxy = ips[i]
        elif roles[i] == "worker":
            ips_worker.append(ips[i])
        elif roles[i] == "monitor":
            monitor = ips[i]
        else:
            raise Exception("Unkown Error!")

    if record.test("ssh_dependence"):
        dependence()
        record.record("ssh_dependence")
    if record.test("ssh_shake"):
        ssh_belive_eachother(ips, roles)
        record.record("ssh_shake")
    if record.test("host"):
        init_env(ips, hosts)
        record.record("host")
    if record.test("yum-install"):
        Y.install_yum_source()
        record.record("yum-install")
    if record.test("yum-source"):
        Y.set_yum_source(ips_worker, proxy)
        record.record("yum-source")
    worker.main(ips_worker, proxy)
    ha_setup.main(ips_worker, dev[0].split("\n")[0], monitor)
    iop().run(ips_worker)
Пример #18
0
from optparse import OptionParser as op
from sys import argv


def gethash(a, i, file):
    if file:
        f = open(i, "rb")
        tohash = f.read()
    else:
        tohash = i
    exec("print({}({}).hexdigest())".format(a, tohash))


if __name__ == '__main__':
    algorithms = algorithms_guaranteed
    opt = op("Usage:%prog [options] [values]")
    opt.add_option("-w",
                   "--word",
                   type="string",
                   help="Set word or to hash",
                   default=None,
                   dest="word")
    opt.add_option("-a",
                   "--algorithm",
                   type="string",
                   help="Set algorithm",
                   default="md5",
                   dest="algorithm")
    opt.add_option(
        "-f",
        "--file",
Пример #19
0
def main():
    version_msg = "%prog Version 0.1 (initial build)"
    usage_msg = '''%prog [OPTIONS]
   A tool helps you download fictions from https://www.biquge.com.cn
   to local environment or send to designated email receiver.'''

    parser = op(version=version_msg, usage=usage_msg)
    parser.add_option(
        "-d",
        action="store",
        dest="downloadBook",
        help="Search for a book and return the first result in the list.")
    parser.add_option("-n",
                      action="store",
                      dest="lastNchapter",
                      help="Download the last N chapters")
    parser.add_option("-r",
                      action="store",
                      dest="receiver",
                      help="Set receiver email address")
    parser.add_option("-u",
                      "--url",
                      action="store",
                      dest="fictionURL",
                      help="Set download URL")
    parser.add_option("-s",
                      "--send",
                      action="store",
                      dest="send",
                      help="Send local file to email")

    options, args = parser.parse_args(sys.argv[1:])

    bookName = options.downloadBook
    lastNchapter = options.lastNchapter
    receiver = options.receiver
    url = options.fictionURL
    send = options.send

    if bookName is None and url is None:
        print("At least one input required!")
        exit()
    elif bookName and url:
        print("Too many inputs")
        exit()

    if bookName:
        fictionBot = FictionBot(bookName)

    if url:
        fictionBot = FictionBot(url=url)

    if lastNchapter:
        book, localPath = fictionBot.download(lastNchapter)
    else:
        book, localPath = fictionBot.download()

    if send:
        MailDelegate.sendEmail(Auth.login, Auth.passwd, receiver, localPath,
                               "text.txt")
    if receiver:
        MailDelegate.sendEmail(Auth.login, Auth.passwd, receiver, localPath,
                               book)
Пример #20
0
def main():
    proxy = None
    monitor = None
    ips_worker = []
    ips = []
    roles = []
    hosts = []
    dev = []
    record = recorder()
    Y = yum()
    usage = "usage: %prog options"
    option = op(usage)
    option.add_option("-f","--file",default=False,action="store",dest="filename",help="point the config file",metavar="FILE")
    option.add_option("-i","--ips",default=False,action="store",dest="ips",help="point the ips except file",metavar="Ips")
    (options,arg) = option.parse_args()
    if not options.filename and not options.ips:
        option.print_help()
        return 
    if options.filename != False:
        if not os.path.exists(options.filename):
            print "ERROR : [ main ] config file is not existed."
            return
        reader = open(options.filename)
        configs = reader.readlines()
        reader.close()
        for config in configs:
            temp = config.split(":")
            if temp[0] == "proxy" or temp[0]=="worker" or temp[0]=="monitor":
                roles.append(temp[0].strip())
                ips.append(temp[1].strip())
            elif temp[0] == "proxyhost" or temp[0] == "workerhost" or temp[0] == "monitorhost":
                hosts.append(temp[1].split("\n")[0])
            elif temp[0]=="device":
                dev.append(temp[1])
            else:
                raise Exception("config file is wrong,please check it.")
    else :
        ips = options.ips.split(",")
        for i in range (len(ips)):
            if i == 0:
                roles.append("proxy")
            else:
                roles.append("worker")
    for i in range(len(ips)):
        if roles[i]=="proxy":
            proxy = ips[i]
        elif roles[i]=="worker":
            ips_worker.append(ips[i])
        elif roles[i] == "monitor":
            monitor = ips[i]
        else:
            raise Exception("Unkown Error!")

    if record.test("ssh_dependence"):
        dependence()
        record.record("ssh_dependence")
    if record.test("ssh_shake"):
        ssh_belive_eachother(ips,roles)
        record.record("ssh_shake")
    if record.test("host"):
        init_env(ips,hosts)
        record.record("host")
    if record.test("yum-install"):
        Y.install_yum_source()
        record.record("yum-install")
    if record.test("yum-source"):
        Y.set_yum_source(ips_worker,proxy)
        record.record("yum-source")
    worker.main(ips_worker,proxy)
    ha_setup.main(ips_worker,dev[0].split("\n")[0],monitor)
    iop().run(ips_worker)
Пример #21
0
def main():
    '''
    Our main application
    '''

    parser = op("usage ipblisted.py --ip [ip]")
    parser.add_option('--proxy',
                      action="store",
                      dest="proxy",
                      help="Useful for when behind a proxy")
    parser.add_option('--proxy_user', action="store", dest="proxy_user")
    parser.add_option('--proxy_pass', action="store", dest="proxy_pass")
    parser.add_option('--good',
                      default=False,
                      action="store_true",
                      dest="show_good",
                      help="Displays lists that the IP did NOT show up on.")
    parser.add_option('--skip-dnsbl',
                      default=False,
                      action="store_true",
                      dest="skip_dnsbl",
                      help="Skips the checking DNS Blacklists")
    parser.add_option('--skip-bl',
                      default=False,
                      action="store_true",
                      dest="skip_bl",
                      help="Skips the checking of text based blacklists")
    parser.add_option(
        '--no-cache',
        default=False,
        action="store_true",
        dest="no_cache",
        help="This will prevent caching of text based blacklists")
    parser.add_option('--clear-cache',
                      default=False,
                      action="store_true",
                      dest="clear_cache",
                      help="This will clear the existing cache")
    parser.add_option(
        '--cache-timeout',
        default=60 * 60 * 12,
        action="store",
        dest="cache_timeout",
        help=
        "Number of seconds before cache results are to expire (Default: 12 hours)"
    )
    parser.add_option('--threads',
                      default=5,
                      action="store",
                      dest="threads",
                      help="Sets the number of feed search threads")
    parser.add_option('--infile',
                      default=None,
                      action="store",
                      dest="infile",
                      help="A newline separated list of IP addresses")
    parser.add_option('--ip', action="store", dest="ip")
    parser.add_option(
        '-w',
        '--wan',
        action="store_true",
        dest="wan",
        default=False,
        help="Will add your WAN ip to the list of IP addresses being checked.")
    parser.add_option('-f',
                      '--format',
                      action="store",
                      dest="format",
                      help="Set the output format for an outfile",
                      default="csv")
    parser.add_option('-o',
                      '--outfile',
                      action="store",
                      dest="outfile",
                      help="Where to write the results",
                      default=None)
    (options, args) = parser.parse_args()

    if options.format:
        allowed_formats = ['csv', 'xls', 'xlsx', 'txt']
        if not options.format in allowed_formats:
            cprint(
                "[!] Invalid format \"{}\".  Please select a valid format {}".
                format(options.format, ', '.join(allowed_formats)), RED)
            sys.exit(1)

    if options.outfile:
        print("[*] Results will be saved to {} in {} format".format(
            options.outfile, options.format))

    # Check if the user supplied an IP address or IP block
    if options.ip is None and options.infile is None and options.wan is False:
        print(
            "[!] You must supply an IP address, the WAN flag or a file containing IP addresses."
        )
        sys.exit(1)

    # Set our list of IPs to an empty list
    ips = []

    # Load up the IP in the --ip flag
    if options.ip:
        if '\\' in options.ip or '/' in options.ip:
            cprint(
                "[!] Detected CIDR notation, adding all IP addresses in this range",
                BLUE)
            for ip in IPSet([options.ip]):
                ips += [str(ip)]
        elif len(options.ip.split(',')) > 0:
            ips += [ip for ip in options.ip.split(',')
                    if ip != '']  # Handles when user does ,%20
        else:
            ips += [options.ip]

    # If the user supplied a file load these as well
    if options.infile:
        ips += [
            ip for ip in file(options.infile).read().split('\n') if ip != ''
        ]

    if options.wan:
        ip = wan_ip()
        if ip:
            ips += [ip]
        else:
            cprint(
                "[!] There was an issue trying to gather the WAN IP address.",
                RED)

    # Check if the user set their credentials when using a proxy
    if options.proxy:
        if options.proxy_user is None or options.proxy_pass is None:
            cprint(
                "[!] Warning, no proxy credentials supplied.  Authenticated proxies may not work.",
                BLUE)
        else:
            options.proxy_pass = urllib.quote(options.proxy_pass)

    # Initialize a queue for the feeds to go in
    fq = Queue()

    # Load in all the feeds from the feed configuration file
    feeds = load_feeds({
        "skip_bl": options.skip_bl,
        "skip_dnsbl": options.skip_dnsbl
    })

    # Establish the requests cache
    if not options.no_cache:
        requests_cache.install_cache('ipblisted',
                                     expire_after=int(options.cache_timeout))

        # If the user wants to manually clear the cache, do it now
        if options.clear_cache:
            requests_cache.clear()

    # If there are no feeds set, just exit the program
    if len(feeds) == 0:
        cprint(
            "[!] No feeds were defined, please define them in feeds.json or don't skip them all.",
            RED)
        sys.exit(1)

    # Final check to make sure we actually have a list of IP addresses to check
    if len(ips) == 0:
        cprint(
            "[!] No IP addresses were listed to check.  Please check your syntax and try again.",
            RED)

    feed_results = []

    # Loop through each IP and find it
    print("[*] Checking {} IP addresses against {} lists".format(
        len(ips), len(feeds)))
    for ip in ips:

        print("[*] Searching Blacklist feeds for IP {ip}".format(ip=ip))

        # Build the feed requests queue
        oq = Queue()

        # Create a queue of all the feeds we want to check
        [fq.put(f) for f in feeds]
        qsize = fq.qsize()

        # Start up our threads and start checking the feeds
        threads = [
            FeedThread(ip, options, fq, oq) for i in range(0, options.threads)
        ]
        [t.start() for t in threads]
        [t.join() for t in threads]

        # Set the number of lists we have found to 0
        find_count = 0

        # Go through each feed and see if we find the IP or block
        results = [r for r in oq.queue]

        if options.outfile:
            convert_results(results, ip, options.outfile)

        # Print out if the IP was found in any of the feeds
        for result in results:

            output = "[*] {name}: {found}".format(**result)

            if result["found"] == "Found":
                find_count += 1
                cprint(output, RED)
                continue

            if options.show_good:
                cprint(output)

        if find_count == 0:
            cprint("[*] Not found on any defined lists.", GREEN)
        else:
            cprint("[*] Found on {}/{} lists.".format(find_count, qsize), RED)
        print("[-]")
Пример #22
0
def main():
	opt = op("Usage: %prog [args] [values]")
	opt.add_option("-d", "--dic",dest="dic",default="dic.txt",help="Set diccionary file")
	(o, argv) = opt.parse_args()
	loaddic(o.dic)
	translated = 
Пример #23
0
import queen_dfs
import queen_hill1

print "*****************", '\n', "Choose options to solve N-queen problem", '\n', "1:DFS", '\n', "2:Hill Climbing", '\n', "3:both"
choice = int(input("\n"))

if choice == 1:
    start = timeit.default_timer()
    queen_dfs.searchCol(0)
    print queen_dfs.sols
    stop = timeit.default_timer()
    time = stop - start
    print "time complexity", time
elif choice == 2:
    start1 = timeit.default_timer()
    parser = op()
    parser.add_option("-e",
                      "--exit",
                      dest="move_style",
                      action="store_false",
                      default=True)

    parser.add_option("--moves", dest="moves", default=1, type="int")

    (options, args) = parser.parse_args()

    temp_board = queen_hill1.queens(move_style=options.move_style,
                                    moves=options.moves)
    temp_board.printstats()
    stop1 = timeit.default_timer()
    time1 = stop1 - start1
Пример #24
0
#-*-coding: utf-8
#https://www.nostarch.com/crackingcodes
from lib import pyperclip
from optparse import OptionParser as op
from sys import argv
if __name__ == '__main__':
    SYMBOLS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?"
    opt = op("Usage: %prog [flag] [value]")
    opt.add_option("-d",
                   "--do",
                   dest="do",
                   default="encode",
                   help="if de value is diferent to 'encode', it decodes.")
    opt.add_option("-k",
                   "--key",
                   dest="key",
                   default=3,
                   help="set key",
                   type="int")
    (o, argv) = opt.parse_args()
    text = input("Input your text: ")
    translated = ""
    for symbol in text:
        if symbol in SYMBOLS:
            symbol_index = SYMBOLS.find(symbol)
            if o.do == "encode":
                translateindex = symbol_index + o.key
            else:
                translateindex = symbol_index - o.key
            if translateindex >= len(SYMBOLS):
                translateindex -= len(SYMBOLS)
Пример #25
0
                    if len(self.missions) == 0:
                        self.missions[cmd[12:count]] = cmd[count + 1:]
                else:
                    count += 1
        elif cmd == "**You are death.":
            print(cmd)
            exit()
        else:
            print(cmd)

    def combat(self):
        pass


if __name__ == '__main__':
    opt = op("Usage: %prog [usage] [value]")
    opt.add_option(
        "-s",
        "--server",
        dest="server",
        help=
        "Set server's ip. (default value = 127.0.0.1) (value's type = string)",
        default="127.0.0.1",
        type="string")
    opt.add_option(
        "-p",
        "--port",
        dest="port",
        help="Set server's port. (default value = 5000) (type = int)",
        default=5000,
        type="int")