def getUser(self, username, server): # 连接服务器 time.sleep(3) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((config.server_name, config.remote_server_port)) sock.settimeout(15) # 检测服务器是否关闭 except Exception: info("connection error", "error") return None sock.send('{"action":"login","uid":0,"username":"******","ip":"%s"}' % (username, server)) userdata = sock.recv(1024) print userdata u = user.user() u.set(json.loads(userdata)) while True: print "[FLOATER FIND] try to find fellow" sock.send('{"action":"find"}') fellow = sock.recv(1024) if fellow != "None": print "[FLOATER FOUND]", fellow userData = json.loads(fellow) u.set(userData) break time.sleep(3) sock.send('{"action":"close"}') sock.close() global username_remote username_remote = userData["username"] global server_name_remote server_name_remote = userData["ip"]
def getUser(self, username, server): #连接服务器 time.sleep(3) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((config.server_name, config.remote_server_port)) sock.settimeout(15) #检测服务器是否关闭 except Exception: info("connection error", "error") return None sock.send('{"action":"login","uid":0,"username":"******","ip":"%s"}' % (username, server)) userdata = sock.recv(1024) print userdata u = user.user() u.set(json.loads(userdata)) while True: print "[FLOATER FIND] try to find fellow" sock.send('{"action":"find"}') fellow = sock.recv(1024) if fellow != "None": print "[FLOATER FOUND]", fellow userData = json.loads(fellow) u.set(userData) break time.sleep(3) sock.send('{"action":"close"}') sock.close() global username_remote username_remote = userData["username"] global server_name_remote server_name_remote = userData["ip"]
class ClientPostOffice(object): """docstring for PostOffice""" def __init__(self): pass def send(self, username, server_name_remote): """This function is use for sending threading""" mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # wait 1 second before connection time.sleep(1) while True: try: mySocket.connect((server_name_remote, config.server_port)) break except socket.error, msg: info( 'connect failed. Error Code : %s %s' % (str(msg[0]), msg[1]), "error") time.sleep(1) info("start send thread", "info") while True: # get a message from the send_queue and then send the message to remote message = send_queue.get() send_queue.task_done() try: mySocket.send(message) info("a message has sent to remote", "info") except Exception as e: info(e, "error") break
def receive(self, username, server_name_remote): mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) time.sleep(1) try: mySocket.bind((server_name_remote, config.image_server_port)) except socket.error, msg: info("connect failed. Error Code : %s %s" % (str(msg[0]), msg[1]), "error") return False
def receive(self, username, server_name_remote): mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) time.sleep(1) try: mySocket.bind((server_name_remote, config.image_server_port)) except socket.error, msg: info('connect failed. Error Code : %s %s' % (str(msg[0]), msg[1]), "error") return False
def main(): # for ret in ai: # ret() command=input("what about?:") if 'services' in command: services.serv() elif 'info'in command: info.info()
def process_request(self): """ Abarbeiten des eigentlichen Request. Die ObjectApplication ruft automatisch die eigentlichen Programmteile auf """ self.check_rights() # Als erstes die Rechte checken! self.setup_naviTABs() self.setup_request_objects() self.setup_context() pathInfo = self.request.environ.get('PATH_INFO', '/') pathInfo = urllib.unquote(pathInfo) try: pathInfo = unicode(pathInfo, "utf-8") except: pass if pathInfo in ("", "/"): # Weiterleitung zum browser url = posixpath.join(self.request.environ['APPLICATION_REQUEST'], "browse") self.response.write("<h1>PathInfo: '%s'</h1>" % pathInfo) self.response.write("<h1>url: '%s'</h1>" % url) raise HttpMoved(url) elif pathInfo.startswith("/info"): # Informations-Seite import info info.info(self.request, self.response) elif pathInfo.startswith("/browse"): # Browser/Download path = pathInfo.lstrip("/browse") import browse FileIter = browse.browser(self.request, self.response, path).get() if FileIter != None: return FileIter elif pathInfo.startswith("/upload/status"): from upload import UploadStatus UploadStatus(self.request, self.response) elif pathInfo.startswith("/upload"): import upload upload.Uploader(self.request, self.response) elif pathInfo.startswith("/newest"): import newestFiles newestFiles.NewestFiles(self.request, self.response) else: self.response.write("<h1>PathInfo: '%s'</h1>" % pathInfo) return self.response
def command_long_text(m): ''' Este método, si el comando enviado es 'info', 'Info', 'i' o 'I', recibe el mensaje enviado por el usuario, obtiene el número de usuario si está autorizado a interactuar con el bot. Si está autorizado, llama a la función info, pasándole el mensaje del usuario y la información del bot. @params m, Mensaje recibido de parte del usuario. @return: nothing ''' if (compruebaUsuario(m)): info.info(m, bot)
def send(self, username, server_name_remote): """This function is use for sending threading""" mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # wait 1 second before connection time.sleep(1) while True: try: mySocket.connect((server_name_remote, config.image_server_port)) break except socket.error, msg: info("connect failed. Error Code : %s %s" % (str(msg[0]), msg[1]), "error") time.sleep(1)
def gamification(): website_address = [ 'https://github.com/matthann/CS3012-LCA-DAG', 'https://github.com/juliaellen/CS3012', 'https://github.com/dowlind1/CS3012' ] df_cq_0 = info.info( 'https://github.com/beltonn/final-assignment-1-3rd-year') df_names = locals() for i in range(3): df_names['df_cq' + str(i)] = info.info(website_address[i]) df_cq_0 = df_cq_0.append(df_names['df_cq' + str(i)]) maintain_test = [] create_test = [] maintain_fun = [] create_fun = [] test_total = [] fun_total = [] gamification = [] for i in range(4): maintain_test.append(float(df_cq_0[i:i + 1]['No.maintain_test_commit'])) create_test.append(float(df_cq_0[i:i + 1]['No.create_test_commit'])) maintain_fun.append( float(df_cq_0[i:i + 1]['No.maintain_function_commit'])) create_fun.append(float(df_cq_0[i:i + 1]['No.create_function_commit'])) test_total.append(float(df_cq_0[i:i + 1]['No.test_commit'])) fun_total.append(float(df_cq_0[i:i + 1]['No.function_commit'])) gamification.append(float(df_cq_0[i:i + 1]['gamification'])) for i in range(len(create_test)): maintain_test[i] = maintain_test[i] + 1 create_test[i] = create_test[i] + 1 maintain_fun[i] = maintain_fun[i] + 1 create_fun[i] = create_fun[i] + 1 #获取test和function的engagement分数: test_score = [] fun_score = [] for i in range(len(maintain_test)): test_score.append((maintain_test[i] + create_test[i]) * create_test[i] / maintain_test[i]) fun_score.append((maintain_fun[i] + create_fun[i]) * create_fun[i] / maintain_fun[i]) return test_score, fun_score, gamification
def send(self, username, server_name_remote): """This function is use for sending threading""" mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # wait 1 second before connection time.sleep(1) while True: try: mySocket.connect((server_name_remote, config.server_port)) break except socket.error, msg: info( 'connect failed. Error Code : %s %s' % (str(msg[0]), msg[1]), "error") time.sleep(1)
def connector(title): info.info(title) gameId = sys.argv[1] sock = getConnection() data = receive_Line(sock) print ("Daten: %s" % (data)) data = 'VERSION 1.0\n' send_Line(sock, data) data = receive_Line(sock) print ("Daten: %s" % (data)) sock.close()
def new_command(context): """ args: context : dictionary including 'title', 'tag', 'genre' and 'config' """ dt = datetime.datetime.today() # make directory and filepath filepath = create_filepath(context['config'].articlepath, dt) # make relative file path rpath = filepath[len(context['config'].articlepath):] print("made" + filepath) # make info data file_info =\ info.info(title=context['title'], tag=context['tag'],\ genre=context['genre'], path=rpath, createDate=dt) print(file_info.dump_json()) # save info data file_info.save_info(context['config'].infopath) # write header write_header(file_info, context['config'].articlepath) # open file by editor os.system(context['config'].editor + " " + filepath)
def __init__(self, input_file): # Load info self.info = info(input_file) # Setup likelihood self.likelihood = likelihood_dict(self.info["likelihoods"]) # DEBUG from plots import plot_likelihood_pdf plot_likelihood_pdf(self.likelihood, self.info["params"]) # Setup samples_set and sampler self.samples = samples_set(self.info["params"]) self.sampler = initialise_sampler(self.likelihood.loglik, lambda x: 1, self.samples, self.info["params"], self.info["sampler"], self.show_updated_info) # Room for parallelisation # n_processes = 1 # n_times_pool = 2 # Fire sampler status = self.sampler.run() self.final_report() return
def _analyze_wait( self, mutant, response ): ''' Analyze results of the _sendMutant method that was sent in the _with_time_delay method. ''' # # Only one thread at the time can enter here. This is because I want to report each # vulnerability only once, and by only adding the "if self._hasNoBug" statement, that # could not be done. # if True: # # I will only report the vulnerability once. # if self._hasNoBug( 'osCommanding' , 'osCommanding' , mutant.getURL() , mutant.getVar() ): if response.getWaitTime() > (self._original_wait_time + self._wait_time-2) and \ response.getWaitTime() < (self._original_wait_time + self._wait_time+2): sentOs, sentSeparator = self._get_os_separator(mutant) # This could be because of an osCommanding vuln, or because of an error that # generates a delay in the response; so I'll resend changing the time and see # what happens original_wait_param = mutant.getModValue() more_wait_param = original_wait_param.replace( \ str(self._wait_time), \ str(self._second_wait_time) ) mutant.setModValue( more_wait_param ) response = self._sendMutant( mutant, analyze=False ) if response.getWaitTime() > (self._original_wait_time + self._second_wait_time-3) and \ response.getWaitTime() < (self._original_wait_time + self._second_wait_time+3): # Now I can be sure that I found a vuln, I control the time of the response. v = vuln.vuln( mutant ) v.setPluginName(self.getName()) v.setName( 'OS commanding vulnerability' ) v.setSeverity(severity.HIGH) v['os'] = sentOs v['separator'] = sentSeparator v.setDesc( 'OS Commanding was found at: ' + mutant.foundAt() ) v.setDc( mutant.getDc() ) v.setId( response.id ) v.setURI( response.getURI() ) kb.kb.append( self, 'osCommanding', v ) else: # The first delay existed... I must report something... i = info.info() i.setPluginName(self.getName()) i.setName('Possible OS commanding vulnerability') i.setId( response.id ) i.setDc( mutant.getDc() ) i.setMethod( mutant.getMethod() ) i['os'] = sentOs i['separator'] = sentSeparator msg = 'A possible OS Commanding was found at: ' + mutant.foundAt() msg += 'Please review manually.' i.setDesc( msg ) kb.kb.append( self, 'osCommanding', i )
def __init__(self, restaurant_dict=dict()): self.id = "" self.info = info() self.max_capacity = 0 self.menu_items = [] if len(restaurant_dict) != 0: self.load_restaurant_from_dict(restaurant_dict)
def cargar(self,informacion): agregar = info(informacion,None) if self.ultimo==None: self.ultimo=agregar else: agregar.next=self.ultimo self.ultimo=agregar return "agregado a la lista"
def main(): parser = argparse.ArgumentParser(description='Band Protocol Layer') parser.add_argument('instruction', help='Instruction sets') parser.add_argument('--debug', dest='debug', action='store_true') parser.add_argument('--key', help='Key to find value') args = parser.parse_args() if args.instruction == 'node': node(args.debug) elif args.instruction == 'init': init() elif args.instruction == 'clear': clear() elif args.instruction == 'info': info(args.key) else: raise Exception("This instruction is not supported")
def main(): start_time = datetime.now() class ArgsException(Exception): pass # класс исключения наличия аргумента class NameException(Exception): pass # класс исключения уникальности имен файлов try: if (args.lowercase and args.uppercase) or (not args.lowercase and not args.uppercase): # проверка наличия аргумента {u|l} raise ArgsException() if args.fpin == args.fpout : # проверка имен файлов на уникальность raise NameException() checkline.checkline(args.fpin, linelist, counts, fpin_path) convert.convert(linelist, args.fpout, args.verbose, fpin_path, low, up) if args.verbose: info.info(args.fpin, args.fpout, workdir, counts) except ArgsException: print("\nОшибка! Ожидается обязательный параметр -l --lowercase или -u --uppercase.\n") except NameException: print("\nОшибка! Имена входного и выходного файла должны отличаться.\n") print(datetime.now() - start_time)
def __init__(self, order_dict=dict()): self.order_id = "" self.customer_id = "" self.info = info() self.max_distance = 0.0 self.order_items = [] if len(order_dict) != 0: self.load_order_from_dict(order_dict)
def main(argv): # Handle the command line arguments # We're all set. Time to configure them settings args = { "project_name": "", "config_file": "", "verbose": False, } if "-h" in argv or "--help" in argv or not argv: info.help() # I need somebody elif argv[0] == "-V" or argv[0] == "--version": info.info() else: # Check for mistakes in the arguments first if not util.arguments_valid(argv): sys.exit(2) if (argv.count("-c") > 1 or argv.count("-s") > 1 or argv.count("-v") > 1 or argv.count("--verbose") or util.fragment_count_in_list(argv, "--config=") > 1 or util.fragment_count_in_list(argv, "--scripts=") > 1 or not util.project_name_specified(argv)): info.help() # Not just anybody sys.exit(2) if not util.locate_project_name(argv): info.help() # You know I need somebody, help sys.exit(2) # Finished validating the passed arguments args["project_name"] = util.locate_project_name(argv) args["config_file"] = util.locate_config_file_in_args(argv) args["verbose"] = util.check_verbose(argv) # Time to create the directories if not skeleton_creator.create_skeleton(args): sys.exit(1) # Now, run the plugin (a.k.a plugins) run_plugins.run_plugins(args["verbose"]) sys.exit(0)
def __init__(self, remoteShell, domainAdmin="admin", domain=None): self.remoteShell = remoteShell self.vastoolPath = "/opt/quest/bin/vastool" self.domainAdmin = domainAdmin self.defaultDomain = domain self.info = info.info(self.run) self.flush = flush.flush(self.run) self.create = create.create(self.run, self.defaultDomain) self.delete = delete.delete(self.run) self.timesync = timesync.timesync(self.run) self.nss = nss.nss(self.run) self.group = group.group(self.run) self.isvas = isvas.isvas(self.run) self.list = list.list(self.run) self.auth = auth.auth(self.run, self.defaultDomain) self.cache = cache.cache(self.run) self.configure = configure.configure(self.run) self.configureVas = configureVas.configureVas(self.run) self.schema = schema.schema(self.run) self.merge = merge.merge(self.run) self.unmerge = unmerge.unmerge(self.run) self.user = User.user(self.run) self.ktutil = ktutil.ktutil(self.run) self.load = load.load(self.run) self._license = License.License(self.run) self.License = self._license.License self.parseLicense = self._license.parseLicense self.compareLicenses = self._license.compareLicenses #self.vasUtilities = vasUtilities.vasUtilities(self.remoteShell) self.unconfigure = unconfigure.unconfigure(self.run) self.nssdiag = nssdiag(self.run) isinstance(self.info, info.info) isinstance(self.flush, flush.flush) isinstance(self.create, create.create) isinstance(self.delete, delete.delete) isinstance(self.timesync, timesync.timesync) isinstance(self.nss, nss.nss) isinstance(self.group, group.group) isinstance(self.isvas, isvas.isvas) isinstance(self.list, list.list) isinstance(self.auth, auth.auth) isinstance(self.cache, cache.cache) isinstance(self.configure, configure.configure) isinstance(self.configureVas, configureVas.configureVas) isinstance(self.schema, schema.schema) isinstance(self.merge, merge.merge) isinstance(self.unmerge, unmerge.unmerge) isinstance(self.user, User.user) isinstance(self.ktutil, ktutil.ktutil) isinstance(self.load, load.load) #isinstance(self.vasUtilities, vasUtilities.vasUtilities) isinstance(self.unconfigure, unconfigure.unconfigure) isinstance(self.nssdiag, nssdiag)
def _analyze_wait(self, mutant, response): ''' Analyze results of the _sendMutant method that was sent in the _fuzz_with_time_delay method. ''' # # Only one thread at the time can enter here. This is because I want to report each # vulnerability only once, and by only adding the "if self._hasNoBug" statement, that # could not be done. # if True: # # I will only report the vulnerability once. # if self._hasNoBug('eval', 'eval', mutant.getURL(), mutant.getVar()): if response.getWaitTime() > (self._original_wait_time + self._wait_time - 2) and \ response.getWaitTime() < (self._original_wait_time + self._wait_time + 2): # generates a delay in the response; so I'll resend changing the time and see # what happens originalWaitParam = mutant.getModValue() moreWaitParam = originalWaitParam.replace( \ str(self._wait_time), \ str(self._second_wait_time) ) mutant.setModValue(moreWaitParam) response = self._sendMutant(mutant, analyze=False) if response.getWaitTime() > (self._original_wait_time + self._second_wait_time - 3) and \ response.getWaitTime() < (self._original_wait_time + self._second_wait_time + 3): # Now I can be sure that I found a vuln, I control the time of the response. v = vuln.vuln(mutant) v.setPluginName(self.getName()) v.setId(response.id) v.setSeverity(severity.HIGH) v.setName('eval() input injection vulnerability') v.setDesc('eval() input injection was found at: ' + mutant.foundAt()) kb.kb.append(self, 'eval', v) else: # The first delay existed... I must report something... i = info.info() i.setPluginName(self.getName()) i.setMethod(mutant.getMethod()) i.setURI(mutant.getURI()) i.setId(response.id) i.setDc(mutant.getDc()) i.setName('eval() input injection vulnerability') msg = 'eval() input injection was found at: ' + mutant.foundAt( ) msg += ' . Please review manually.' i.setDesc(msg) kb.kb.append(self, 'eval', i)
def data(): website_address = ['https://github.com/matthann/CS3012-LCA-DAG', 'https://github.com/juliaellen/CS3012', 'https://github.com/dowlind1/CS3012'] df_cq_0=info.info('https://github.com/beltonn/final-assignment-1-3rd-year') df_cq_0.insert(df_cq_0.shape[1], 'num', '0') df_cq_node = df_cq_0[0:1] df_cq_LCA = df_cq_0[1:2] df_cq_TEST = df_cq_0[2:3] #print(df_cq_node) #print(df_cq_LCA) #print(df_cq_TEST) df_names = locals() for i in range(3): df_names['df_cq' + str(i) ] = info.info(website_address[i]) df_names['df_cq' + str(i) ].insert(df_names['df_cq' + str(i) ].shape[1], 'num', str(i+1)) ''' if df_names['df_cq' + str(i) ][i:i+1][['file_name']].find("Node")>=0: df_cq_node.append(df_names['df_cq' + str(i) ][i:i+1]) else: pass ''' df_cq_0=df_cq_0.append(df_names['df_cq' + str(i) ]) #给数据框编上序号 seq = df_cq_0[0:1] seq.insert(df_cq_0.shape[1],'id',0) for i in range(len(df_cq_0)-1): #df_cq_0 = df_cq_0[i:i+1].insert(df_cq_0.shape[1], 'id', str(i)) x = df_cq_0[i+1:i+2] x.insert(df_cq_0.shape[1],'id',str(i+1)) seq = seq.append(x) #print(df_cq_0) print(seq) #print(df_cq_0) return seq
def check(package): md, files = info.info(package, True) corrupt = [] for file in files.list: if file.hash and file.type != "config" \ and not os.path.islink('/' + file.path): ctx.ui.info(_("Checking %s ") % file.path, noln=True, verbose=True) if file.hash != util.sha1_file('/' + file.path): corrupt.append(file) ctx.ui.info("Corrupt file: %s" % file) else: ctx.ui.info("OK", verbose=True) return corrupt
def SubClient(self, indice): msgUsername = self.connexions[indice].recv(1024).decode() print("msgUsername reçu : %s" % (msgUsername)) msgVille = self.connexions[indice].recv(1024).decode() print("msgVille reçu : %s" % (msgVille)) msgHobby = self.connexions[indice].recv(1024).decode().split(" ") print("msgHobby reçu : %s" % (msgHobby)) info_client = info(indice, msgUsername, msgVille, msgHobby) self.user.append(info_client) print(info_client.show_fiche())
def handle(self): engine = create_engine(options.db_path, convert_unicode=True, echo=options.debug, pool_size = 100, pool_recycle=7200) engine.connect() db = scoped_session(sessionmaker(bind=engine)) weekTime = datetime.datetime.fromtimestamp(time.time()-7*24*3600).strftime("%Y-%m-%d") #all data from table_ListenLog,while time > 7day time,and song_id != NULL result = db.query(models.ListenLog).filter(and_(models.ListenLog.time > weekTime, models.ListenLog.song != 'NULL')).all() resultJson = []# songs = {} for log in result: if songs.has_key(log.song): isIn = False songInfos = songs[log.song] for songinfo in songInfos: if songinfo.radioId == log.stationId: if log.time < songinfo.time + datetime.timedelta(minutes=10) and log.time > songinfo.time - datetime.timedelta(minutes=10): isIn = True break if isIn == False: songInfos.append(info.info(log.stationId, log.time)) songresult = db.query(models.Song).filter(models.Song.id == log.song).all() resultJson.append( { "time" : str(log.time), "title": songresult[0].name, "artist": songresult[0].artist }) else: songs[log.song] = [info.info(log.stationId, log.time)] songresult = db.query(models.Song).filter(models.Song.id == log.song).all() resultJson.append( { "time" : str(log.time), "title": songresult[0].name, "artist": songresult[0].artist }) print resultJson return json.dumps(resultJson)
def get_info(): # 针对全部城市的采集 collection = MongoClient()['youXin']['all'] city_links = set(shelve_open('all_link')) city_invalid_links = set(shelve_open('invalid_link')) if city_links: # 如果文件里存在链接 in_database = {i['链接'][8:] for i in collection.find()} l_i_d = len(in_database) link_for_catch = city_links - in_database - city_invalid_links l_f_c = len(link_for_catch) print('数据库:{}, 待采集{}, 共{}条'.format(l_i_d, l_f_c, l_i_d + l_f_c)) for i, link in enumerate(link_for_catch): print(i + l_i_d, 'of', l_i_d + l_f_c) # # 页面不存在这种情况也计算在内 doc = info(link) if doc: collection.insert_one(doc) print('完成'.center(30, '*'))
def initialize(): pl.close('all') global info, network, system, traces, torus, sweepingPhasespace reload(model) info = nf.info() network = netw.network(info=info) system = sys.system(info=info, network=network) traces = tra.traces(system, network, info=info) torus = tor.torus(system, network, traces, info=info) network.system = system system.traces = traces ## customize system for web system.setParams(epsilon=0.3) system.ax.set_xlabel(r'Inactivation Variable') system.ax.set_ylabel(r'Voltage Variable') system.ax.set_title('') system.fig.tight_layout() plugins.connect(system.fig, DragPlugin(eventHandlerURL="updatesystem", radioButtonID="systemRadio")) # customize network network.ax.patch.set_facecolor('#777777') network.moveText(2, [0.02, -0.1]) network.moveText(3, [0.02, -0.1]) network.ax.texts[6].set_text('1') network.ax.texts[7].set_text('2') network.ax.texts[8].set_text('3') plugins.connect(network.fig, DragPlugin(eventHandlerURL="updatenetwork", radioButtonID="networkRadio")) # customize traces traces.ax.patch.set_facecolor('#777777') traces.fig.tight_layout() # customize torus torus.ax_traces.set_xlabel(r'phase lag: 1-2') torus.ax_basins.set_xlabel(r'phase lag: 1-2') torus.ax_traces.set_ylabel(r'phase lag: 1-3') torus.fig.tight_layout() torus.switch_processor() # switches on the gpu if available if torus.USE_GPU: torus.setGridsize(24) plugins.connect(torus.fig, ClickPlugin(eventHandlerURL="updatetorus", radioButtonID="torusRadio")) # reload timing variable sweepingPhasespace = False;
def __init__(self, params_file): # Load info self.info = info(params_file) # Setup prior self.prior = prior(self.info["params"]) # Setup likelihood self.likelihood = likelihood_dict(self.info["likelihoods"]) # Consistency checks assert self.likelihood.dimension() == self.prior.dimension(), ( "The dimensionalities of prior and likelihood do not match.") plot_likelihood(self.likelihood, self.prior) # Setup sample_set and sampler self.samples = samples_set(self.info["params"]) # Setup sampler self.sampler = get_sampler(self.info["sampler"])(self.info["sampler"], self.prior, self.likelihood) # n_processes = 1 # n_times_pool = 2 # ERASE THE FORMER LINE!!!! And remove the corresponding paramenters n_diagnosis = 10 # Fire sampler while not(self.sampler.check_convergence()): self.sampler.next_iteration() if not(self.sampler.i_iter%n_diagnosis): self.sampler.diagnosis(prepare_axes)
mySocket.send(message) info("a message has sent to remote", "info") except Exception as e: info(e, "error") break def receive(self, username, server_name_remote): mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) time.sleep(1) try: mySocket.bind((server_name_remote, config.server_port)) except socket.error, msg: info("connect failed. Error Code : %s %s" % (str(msg[0]), msg[1]), "error") return False mySocket.listen(100) info("start image receive thread", "info") connection, address = mySocket.accept() info("connection accepted", "info") while True: try: message = connection.recv(1024) info("receive message from remote: %s" % message, "info") receive_queue.put("%s" % (message)) except Exception as e: info(e, "error") return class ClientImagePostOffice(object): """docstring for PostOffice"""
def start_message(message): ''' Обработчик команды /info ''' BOT.send_message(message.chat.id, info(), parse_mode="HTML")
def commandline(): """zhpy, the python language in chinese Accept options: -i --input: speficy the input source -o --output: speficy the output source -p --python: compile to python and run -c --cmp: input raw zhpy source and run -e --encoding: specify the encoding --info: zhpy information -v --verbose: show zhpy progress in detail --tw: convert python to twpy --cn: convert python to cnpy help: get information: zhpy --info interpreter usage: zhpy [--tw | --cn] command usage: zhpy [-i | -p] input [-o] [output] [-e] [encoding] [-v] :: $ zhpy input.py (.twpy, .cnpy) [arguments] $ zhpy -i input.py (.twpy, .cnpy) $ zhpy -i input.py -o output.py (.twpy, .cnpy) $ zhpy -p input.py script usage: zhpy [-c] source [-e] [encoding] [-v] convertor usage: zhpy [--tw | --cn] input.py [-v] :: $ zhpy --tw input.py [-v] $ zhpy --cn input.py [-v] """ argv = sys.argv[1:] os.chdir(os.getcwd()) source = None target = None encoding = None raw_source = None verbose = False python = False tw = False cn = False # run as interpreter if len(argv) == 0: from interpreter import interpreter interpreter() sys.exit() # run as script # not accept any option elif not argv[0].startswith('-'): source = argv[0] sys.argv = argv # run as command elif len(argv)==1: if argv[0] == '--info': from info import info info() sys.exit() elif argv[0] == '-h' or argv[0] == '--help': print commandline.__doc__ sys.exit() # run as native interpreter elif argv[0] == '--tw': from interpreter import interpreter interpreter('tw') sys.exit() elif argv[0] == '--cn': from interpreter import interpreter interpreter('cn') sys.exit() else: print commandline.__doc__ sys.exit() # accept "-c -e -v" elif len(argv)>=2: if argv[0] == '-c' or argv[0] == '--cmp': raw_source = argv[1] del(argv[:2]) if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True # python to twpy elif argv[0] == '--tw': source = argv[1] filename = os.path.splitext(source)[0] # remove extra .tw in filename profix = os.path.splitext(filename)[-1] if profix =='.tw': filename = os.path.splitext(filename)[0] del(argv[:2]) tw = True target = "v_"+filename+".twpy" if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True # python to cnpy elif argv[0] == '--cn': source = argv[1] filename = os.path.splitext(source)[0] # remove extra .cn in filename profix = os.path.splitext(filename)[-1] if profix == '.cn': filename = os.path.splitext(filename)[0] del(argv[:2]) cn = True target = "v_"+filename+".cnpy" if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True # accept "-i -o -e -v" or "-p -e" or "-c -e -v" elif argv[0] == '-i' or argv[0] == '--input': source = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True if len(argv)>=2 and (argv[0] == '-o' or argv[0] == '--output'): target = argv[1] del(argv[:2]) if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True elif argv[0] == '-p' or argv[0] == '--python': source = argv[1] filename = os.path.splitext(source)[0] del(argv[:2]) target = "n_"+filename+".py" python = True print "compile to python and run: %s"%("n_"+filename+".py") if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True else: print commandline.__doc__ sys.exit() #convert if raw_source: if verbose: print "run raw_source", raw_source annotator() if encoding: result = convertor(raw_source, verbose, encoding) else: result = convertor(raw_source, verbose) try_run(result) sys.exit() if encoding: print "encoding", encoding if source: if verbose: print "input", source # convertor if(tw or cn): if verbose: print "convert python code to", try: from pyzh import rev_annotator, python_convertor test = file(source, "r").read() if tw: print "twpy" rev_annotator('tw', verbose) result = python_convertor(test, lang='tw') if cn: print "cnpy" rev_annotator('cn', verbose) result = python_convertor(test, lang='cn') except Exception, e: print "zhpy Exception: you may input unproper source" if verbose: print e sys.exit() else: try: test = file(source, "r").read() annotator() if encoding: result = convertor(test, verbose, encoding) else: result = convertor(test, verbose) except Exception, e: print "zhpy Exception: you may input unproper source" if verbose: print e sys.exit()
usage() sys.exit(1) srv = server.Server(conf['host'],conf['port'],conf['bufsize']) signal.signal(signal.SIGINT,srv.exit) signal.signal(signal.SIGHUP,srv.exit) signal.signal(signal.SIGQUIT,srv.exit) signal.signal(signal.SIGTERM,srv.exit) for a in args: if a == "start" : if srv.is_running(): info.warning('Issak is already started') sys.exit() else: info.info('Starting Issak\n') srv.start() elif a == "stop": srv.stop() elif a == "status": if srv.is_running(): info.info('Issak is online\n') else: info.info('Issak is offline\n') sys.exit() else: assert False, "unhandled option"
def commandline(): """zhpy, the python language in chinese Accept options: -i --input: speficy the input source -o --output: speficy the output source -p --python: compile to python and run -c --cmp: input raw zhpy source and run -e --encoding: specify the encoding --info: zhpy information -v --verbose: show zhpy progress in detail --tw: convert python to twpy --cn: convert python to cnpy help: get information: zhpy --info interpreter usage: zhpy [--tw | --cn] command usage: zhpy [-i | -p] input [-o] [output] [-e] [encoding] [-v] :: $ zhpy input.py (.twpy, .cnpy) [arguments] $ zhpy -i input.py (.twpy, .cnpy) $ zhpy -i input.py -o output.py (.twpy, .cnpy) $ zhpy -p input.py script usage: zhpy [-c] source [-e] [encoding] [-v] convertor usage: zhpy [--tw | --cn] input.py [-v] :: $ zhpy --tw input.py [-v] $ zhpy --cn input.py [-v] """ argv = sys.argv[1:] os.chdir(os.getcwd()) source = None target = None encoding = None raw_source = None verbose = False python = False tw = False cn = False # run as interpreter if len(argv) == 0: from interpreter import interpreter interpreter() sys.exit() # run as script # not accept any option elif not argv[0].startswith('-'): source = argv[0] sys.argv = argv # run as command elif len(argv) == 1: if argv[0] == '--info': from info import info info() sys.exit() elif argv[0] == '-h' or argv[0] == '--help': print commandline.__doc__ sys.exit() # run as native interpreter elif argv[0] == '--tw': from interpreter import interpreter interpreter('tw') sys.exit() elif argv[0] == '--cn': from interpreter import interpreter interpreter('cn') sys.exit() else: print commandline.__doc__ sys.exit() # accept "-c -e -v" elif len(argv) >= 2: if argv[0] == '-c' or argv[0] == '--cmp': raw_source = argv[1] del (argv[:2]) if len(argv) >= 2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del (argv[:2]) if (len(argv) != 0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True # python to twpy elif argv[0] == '--tw': source = argv[1] filename = os.path.splitext(source)[0] # remove extra .tw in filename profix = os.path.splitext(filename)[-1] if profix == '.tw': filename = os.path.splitext(filename)[0] del (argv[:2]) tw = True target = "v_" + filename + ".twpy" if (len(argv) != 0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True # python to cnpy elif argv[0] == '--cn': source = argv[1] filename = os.path.splitext(source)[0] # remove extra .cn in filename profix = os.path.splitext(filename)[-1] if profix == '.cn': filename = os.path.splitext(filename)[0] del (argv[:2]) cn = True target = "v_" + filename + ".cnpy" if (len(argv) != 0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True # accept "-i -o -e -v" or "-p -e" or "-c -e -v" elif argv[0] == '-i' or argv[0] == '--input': source = argv[1] del (argv[:2]) if (len(argv) != 0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True if len(argv) >= 2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del (argv[:2]) if (len(argv) != 0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True if len(argv) >= 2 and (argv[0] == '-o' or argv[0] == '--output'): target = argv[1] del (argv[:2]) if len(argv) >= 2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del (argv[:2]) if (len(argv) != 0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True elif argv[0] == '-p' or argv[0] == '--python': source = argv[1] filename = os.path.splitext(source)[0] del (argv[:2]) target = "n_" + filename + ".py" python = True print "compile to python and run: %s" % ("n_" + filename + ".py") if (len(argv) != 0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True if len(argv) >= 2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del (argv[:2]) if (len(argv) != 0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True else: print commandline.__doc__ sys.exit() #convert if raw_source: if verbose: print "run raw_source", raw_source annotator() if encoding: result = convertor(raw_source, verbose, encoding) else: result = convertor(raw_source, verbose) try_run(result) sys.exit() if encoding: print "encoding", encoding if source: if verbose: print "input", source # convertor if (tw or cn): if verbose: print "convert python code to", try: from pyzh import rev_annotator, python_convertor test = file(source, "r").read() if tw: print "twpy" rev_annotator('tw', verbose) result = python_convertor(test, lang='tw') if cn: print "cnpy" rev_annotator('cn', verbose) result = python_convertor(test, lang='cn') except Exception, e: print "zhpy Exception: you may input unproper source" if verbose: print e sys.exit() else: try: test = file(source, "r").read() annotator() if encoding: result = convertor(test, verbose, encoding) else: result = convertor(test, verbose) except Exception, e: print "zhpy Exception: you may input unproper source" if verbose: print e sys.exit()
def do_info(self, args): fields = parseFields(self.fields[1:], ( ( (), 'parameter', 'Parameter to display' ), ), 0) info.info(self, fields[0]) return False
import system as sys import network3N as netw import traces as tra import info as nf import torus as tor import pylab as pl pos_info = '+0+600' pos_tra = '+300+600' pos_net = '+300+0' pos_sys = '+0+0' pos_torus = '+800+0' info = nf.info(position=pos_info) net = netw.network(g_inh=0.015, info=info, position=pos_net) system = sys.system(info=info, position=pos_sys, network=net) traces = tra.traces(system, net, info=info, position=pos_tra) torus = tor.torus(system, net, traces, info=info, position=pos_torus) net.system = system system.traces = traces if pl.get_backend() == 'TkAgg': system.fig.tight_layout() traces.fig.tight_layout() torus.fig.tight_layout() pl.show()
def _analyzeResult(self, mutant, response): ''' Analyze results of the _sendMutant method. Try to find the local file inclusions. ''' # # Only one thread at the time can enter here. This is because I want to report each # vulnerability only once, and by only adding the "if self._hasNoBug" statement, that # could not be done. # if True: # # I analyze the response searching for a specific PHP error string that tells me # that open_basedir is enabled, and our request triggered the restriction. If # open_basedir is in use, it makes no sense to keep trying to read "/etc/passwd", # that is why this variable is used to determine which tests to send if it was possible # to detect the usage of this security feature. # if not self._open_basedir: if 'open_basedir restriction in effect' in response\ and 'open_basedir restriction in effect' not in mutant.getOriginalResponseBody(): self._open_basedir = True # # I will only report the vulnerability once. # if self._hasNoBug('localFileInclude', 'localFileInclude', mutant.getURL(), mutant.getVar()): # # Identify the vulnerability # file_content_list = self._find_file(response) for file_pattern_regex, file_content in file_content_list: if not file_pattern_regex.search( mutant.getOriginalResponseBody()): v = vuln.vuln(mutant) v.setPluginName(self.getName()) v.setId(response.id) v.setName('Local file inclusion vulnerability') v.setSeverity(severity.MEDIUM) v.setDesc('Local File Inclusion was found at: ' + mutant.foundAt()) v['file_pattern'] = file_content v.addToHighlight(file_content) kb.kb.append(self, 'localFileInclude', v) return # # If the vulnerability could not be identified by matching strings that commonly # appear in "/etc/passwd", then I'll check one more thing... # (note that this is run if no vulns were identified) # # http://host.tld/show_user.php?id=show_user.php if mutant.getModValue() == mutant.getURL().getFileName(): match, lang = is_source_file(response.getBody()) if match: # We were able to read the source code of the file that is vulnerable to # local file read v = vuln.vuln(mutant) v.setPluginName(self.getName()) v.setId(response.id) v.setName('Local file read vulnerability') v.setSeverity(severity.MEDIUM) msg = 'An arbitrary local file read vulnerability was found at: ' msg += mutant.foundAt() v.setDesc(msg) # # Set which part of the source code to match # match_source_code = match.group(0) v['file_pattern'] = match_source_code kb.kb.append(self, 'localFileInclude', v) return # # Check for interesting errors (note that this is run if no vulns were identified) # for regex in self.get_include_errors(): match = regex.search(response.getBody()) if match and not \ regex.search( mutant.getOriginalResponseBody() ): i = info.info(mutant) i.setPluginName(self.getName()) i.setId(response.id) i.setName('File read error') i.setDesc('A file read error was found at: ' + mutant.foundAt()) kb.kb.append(self, 'error', i)
def checkout_args(args): checkout(info(args.project, args.id), args.destination) pass
def api_info(): return jsonify(info.info())
def __init__(self, system, network, traces, info=None, position=None): torus_2D.torus_2D.__init__(self, system, network, traces, info, position) if __name__ == "__main__": import system as sys import network as netw import traces as tra import info as nf import pylab as pl i = nf.info() s = sys.system(info=i) n = netw.network(info=i) t = tra.traces(s, n, info=i) tor = torus(s, n, t, info=i) pl.show()
if __name__ == "__main__": import pylab as pl import system as sys import network3N as netw import traces as tra import info as nf info = nf.info() system = sys.system(info=info) network = netw.network(info=info) traces = tra.traces(system, network, info=info) t = torus(system, network, traces, info=info) system.torus = t t.vectorField_prc() pl.show()
#!/usr/bin/python from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer import info, display_svg, chart_svg, pickle PORT_NUMBER = 8080 class requestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() # Send the html message self.wfile.write(uss_info.get_html()) return uss_info = info.info() f = open("data/infos.ussinfos", "rb") infos = pickle.load(f) f.close() for i in infos: uss_info.add_info(i[0], i[1]) try: server = HTTPServer(('', PORT_NUMBER), requestHandler) print 'Started httpserver on port ' , PORT_NUMBER server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close()
def commandline(): """zhpy, the python language on chinese Accept options: input: speficy the input source output: speficy the output source python: compile to python and run cmp: input raw zhpy source and run encoding: specify the encoding info: zhpy information verbose: show zhpy progress in detail # zhpy: compile python code to zhpy help: command usage: zhpy [-i|-p] input [-o] [output] [-e] [encoding] [-v] script usage: zhpy [-c] source [-e] [encoding] [-v] $ zhpy input.py (.twpy, .cnpy) [arguments] $ zhpy -i input.py (.twpy, .cnpy) $ zhpy -i input.py -o output.py (.twpy, .cnpy) $ zhpy -p input.py """ argv = sys.argv[1:] os.chdir(os.getcwd()) source = None target = None encoding = None raw_source = None verbose = False python = False # run as interpreter if len(argv) == 0: from interpreter import interpreter interpreter() sys.exit() # run as script # not accept any option elif not argv[0].startswith('-'): source = argv[0] sys.argv = argv # run as command # accept "-i -o -e" or "-p -e" or "-c -e" elif len(argv)==1: if argv[0] == '--info': from info import info info() sys.exit() if argv[0] == '-h' or argv[0] == '--help': print commandline.__doc__ sys.exit() elif len(argv)>=2: if argv[0] == '-c' or argv[0] == '--cmp': raw_source = argv[1] del(argv[:2]) if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if not len(argv) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True elif argv[0] == '-i' or argv[0] == '--input': source = argv[1] del(argv[:2]) if len(argv)>=2 and (argv[0] == '-o' or argv[0] == '--output'): target = argv[1] del(argv[:2]) if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if not len(argv) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True elif argv[0] == '-p' or argv[0] == '--python': source = argv[1] filename = os.path.splitext(source)[0] del(argv[:2]) target = "n_"+filename+".py" python = True print "compile to python and run: %s"%("n_"+filename+".py") if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if not len(argv) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True else: print commandline.__doc__ sys.exit() #convert if raw_source: if verbose: print "run raw_source", raw_source annotator() if encoding: result = convertor(raw_source, encoding) else: result = convertor(raw_source) try_run(result) sys.exit() if encoding: print "encoding", encoding if source: if verbose: print "input", source # convertor test = file(source, "r").read() annotator() if encoding: result = convertor(test, encoding) else: result = convertor(test) if target: if verbose: print "output", target file(target,"w").write(result) if python: try_run(result) else: try_run(result)
def thinker(title): info.info(title)
df0['Total'] = df0['M1'] + df0['M2'] + df0['M3'] + df0['APD'] ops_source.data['x'] = [[df0.iloc[int(m1index), 0], df0.iloc[int(m1index), 0]+lifeslider.value], [df0.iloc[int(m2index), 0], df0.iloc[int(m2index), 0]+lifeslider.value], [df0.iloc[int(m3index), 0], df0.iloc[int(m3index), 0]+lifeslider.value]] print("Mission 1 Last Year of Ops: ", df0.iloc[m1index, 0] + lifeslider.value) print("Mission 3 Launch Year: ", df0.iloc[int(m3index), 0]) years_of_joint_operations = int(np.max([df0.iloc[m1index, 0] + lifeslider.value - df0.iloc[int(m3index), 0], 0]) ) print("Number of Years of Overlapping Operations: ", years_of_joint_operations) a_source.data['year_text'] = [str(years_of_joint_operations)] def update_lifetime(attrname, old, new): ops_source.data['x'] = [[df0.iloc[int(m1index), 0], df0.iloc[int(m1index), 0]+lifeslider.value], [df0.iloc[int(m2index), 0], df0.iloc[int(m2index), 0]+lifeslider.value], [df0.iloc[int(m3index), 0], df0.iloc[int(m3index), 0]+lifeslider.value]] m1index = mission1_wedge(afwslider.value, m1slider.value) m2index = mission2_wedge(afwslider.value, m2slider.value, m1index) m3index = mission3_wedge(afwslider.value, m3slider.value, m2index) for e in [afwslider, m1slider, m2slider, m3slider, lifeslider]: e.on_change('value', update_budget) mission_inputs = row(afwslider, lifeslider, background='rgba(0, 0, 0, 0.0)') mission_budgets = row(m1slider, m2slider, m3slider, background='rgba(0, 0, 0, 0.0)') div = Div(text=info.info(), width=850, height=300) docs = Panel(child=div, title='Info') results = Panel(child = column(mission_inputs, mission_budgets, p0), title='Results') tabs = Tabs(tabs=[results, docs]) curdoc().add_root(tabs) curdoc().title = "Flagship Mission Affordability Calculator"
def commandline(): """zhpy, the python language on chinese Accept options: -i --input: speficy the input source -o --output: speficy the output source -p --python: compile to python and run -c --cmp: input raw zhpy source and run -e --encoding: specify the encoding --info: zhpy information -v --verbose: show zhpy progress in detail help: get information: :: $ zhpy --info interpreter usage: :: $ zhpy $ zhpy --tw $ zhpy --cn command usage: zhpy [-i|-p] input [-o] [output] [-e] [encoding] [-v] :: $ zhpy input.py (.twpy, .cnpy) [arguments] $ zhpy -i input.py (.twpy, .cnpy) $ zhpy -i input.py -o output.py (.twpy, .cnpy) $ zhpy -p input.py script usage: zhpy [-c] source [-e] [encoding] [-v] """ argv = sys.argv[1:] os.chdir(os.getcwd()) source = None target = None encoding = None raw_source = None verbose = False python = False # run as interpreter if len(argv) == 0: from interpreter import interpreter interpreter() sys.exit() # run as script # not accept any option elif not argv[0].startswith('-'): source = argv[0] sys.argv = argv # run as command elif len(argv) == 1: if argv[0] == '--info': from info import info info() sys.exit() elif argv[0] == '-h' or argv[0] == '--help': print commandline.__doc__ sys.exit() # run as native interpreter elif argv[0] == '--tw': from interpreter import interpreter interpreter('tw') sys.exit() elif argv[0] == '--cn': from interpreter import interpreter interpreter('cn') sys.exit() else: print commandline.__doc__ sys.exit() # accept "-c -e -v" or "-i -o -e -v" or "-p -e" or "-c -e -v" elif len(argv) >= 2: if argv[0] == '-c' or argv[0] == '--cmp': raw_source = argv[1] del (argv[:2]) if len(argv) >= 2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del (argv[:2]) if not len(argv) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True elif argv[0] == '-i' or argv[0] == '--input': source = argv[1] del (argv[:2]) if len(argv) >= 2 and (argv[0] == '-o' or argv[0] == '--output'): target = argv[1] del (argv[:2]) if len(argv) >= 2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del (argv[:2]) if not len(argv) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True elif argv[0] == '-p' or argv[0] == '--python': source = argv[1] filename = os.path.splitext(source)[0] del (argv[:2]) target = "n_" + filename + ".py" python = True print "compile to python and run: %s" % ("n_" + filename + ".py") if len(argv) >= 2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del (argv[:2]) if not len(argv) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True else: print commandline.__doc__ sys.exit() #convert if raw_source: if verbose: print "run raw_source", raw_source annotator() if encoding: result = convertor(raw_source, encoding) else: result = convertor(raw_source) try_run(result) sys.exit() if encoding: print "encoding", encoding if source: if verbose: print "input", source # convertor try: test = file(source, "r").read() annotator() if encoding: result = convertor(test, encoding) else: result = convertor(test) except: print "zhpy Exception: you may input unproper source" sys.exit() if target: if verbose: print "output", target file(target, "w").write(result) if python: try_run(result) else: try_run(result)
#!/usr/bin/env python #import Tkinter import system as sys import network as netw import traces as tra import info as nf import torus as tor import pylab as pl #root = Tkinter.Tk() #screen_width = root.winfo_screenwidth() #screen_height = root.winfo_screenheight() pos_info = '+0+600' pos_tra = '+300+600' pos_net = '+300+0' pos_sys = '+0+0' pos_torus = '+800+0' i = nf.info(position=pos_info) s = sys.system(info=i, position=pos_sys) n = netw.network(info=i, position=pos_net) t = tra.traces(s, n, info=i, position=pos_tra) tor = tor.torus(s, n, t, info=i, position=pos_torus) pl.show()
def _analyzeResult( self, mutant, response ): ''' Analyze results of the _sendMutant method. Try to find the local file inclusions. ''' # # Only one thread at the time can enter here. This is because I want to report each # vulnerability only once, and by only adding the "if self._hasNoBug" statement, that # could not be done. # if True: # # I analyze the response searching for a specific PHP error string that tells me # that open_basedir is enabled, and our request triggered the restriction. If # open_basedir is in use, it makes no sense to keep trying to read "/etc/passwd", # that is why this variable is used to determine which tests to send if it was possible # to detect the usage of this security feature. # if not self._open_basedir: if 'open_basedir restriction in effect' in response\ and 'open_basedir restriction in effect' not in mutant.getOriginalResponseBody(): self._open_basedir = True # # I will only report the vulnerability once. # if self._hasNoBug( 'localFileInclude' , 'localFileInclude' , mutant.getURL() , mutant.getVar() ): # # Identify the vulnerability # file_content_list = self._find_file( response ) for file_pattern_regex, file_content in file_content_list: if not file_pattern_regex.search( mutant.getOriginalResponseBody() ): v = vuln.vuln( mutant ) v.setPluginName(self.getName()) v.setId( response.id ) v.setName( 'Local file inclusion vulnerability' ) v.setSeverity(severity.MEDIUM) v.setDesc( 'Local File Inclusion was found at: ' + mutant.foundAt() ) v['file_pattern'] = file_content v.addToHighlight( file_content ) kb.kb.append( self, 'localFileInclude', v ) return # # If the vulnerability could not be identified by matching strings that commonly # appear in "/etc/passwd", then I'll check one more thing... # (note that this is run if no vulns were identified) # # http://host.tld/show_user.php?id=show_user.php if mutant.getModValue() == mutant.getURL().getFileName(): match, lang = is_source_file( response.getBody() ) if match: # We were able to read the source code of the file that is vulnerable to # local file read v = vuln.vuln( mutant ) v.setPluginName(self.getName()) v.setId( response.id ) v.setName( 'Local file read vulnerability' ) v.setSeverity(severity.MEDIUM) msg = 'An arbitrary local file read vulnerability was found at: ' msg += mutant.foundAt() v.setDesc( msg ) # # Set which part of the source code to match # match_source_code = match.group(0) v['file_pattern'] = match_source_code kb.kb.append( self, 'localFileInclude', v ) return # # Check for interesting errors (note that this is run if no vulns were identified) # for regex in self.get_include_errors(): match = regex.search( response.getBody() ) if match and not \ regex.search( mutant.getOriginalResponseBody() ): i = info.info( mutant ) i.setPluginName(self.getName()) i.setId( response.id ) i.setName( 'File read error' ) i.setDesc( 'A file read error was found at: ' + mutant.foundAt() ) kb.kb.append( self, 'error', i )
info("a message has sent to remote", "info") except Exception as e: info(e, "error") break def receive(self, username, server_name_remote): mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) time.sleep(1) try: mySocket.bind((server_name_remote, config.server_port)) except socket.error, msg: info('connect failed. Error Code : %s %s' % (str(msg[0]), msg[1]), "error") return False mySocket.listen(100) info("start image receive thread", "info") connection, address = mySocket.accept() info("connection accepted", "info") while True: try: message = connection.recv(1024) info("receive message from remote: %s" % message, "info") receive_queue.put("%s" % (message)) except Exception as e: info(e, "error") return class ClientImagePostOffice(object): """docstring for PostOffice""" def __init__(self):
import thetax2 as model import torus_2D import numpy as np class torus(torus_2D.torus_2D): model = model V_trigger = np.pi / 2. def __init__(self, system, network, traces, info=None, position=None): torus_2D.torus_2D.__init__(self, system, network, traces, info, position) if __name__ == "__main__": import system as sys import network as netw import traces as tra import info as nf import pylab as pl i = nf.info() s = sys.system(info=i) n = netw.network(info=i) t = tra.traces(s, n, info=i) tor = torus(s, n, t, info=i) pl.show()
def commandline(): """zhpy, the python language in chinese Accept options: -i --input: speficy the input source -o --output: speficy the output source -p --python: compile to python and run -c --cmp: input raw zhpy source and run -e --encoding: specify the encoding --info: zhpy information -v --verbose: show zhpy progress in detail -V --version show zhpy version --tw: convert python to twpy --cn: convert python to cnpy help: get information: zhpy --info interpreter usage: zhpy [--tw | --cn] command usage: zhpy [-i | -p] input [-o] [output] [-e] [encoding] [-v] :: $ zhpy input.py (.twpy, .cnpy) [arguments] $ zhpy -i input.py (.twpy, .cnpy) $ zhpy -i input.py -o output.py (.twpy, .cnpy) $ zhpy -p input.py script usage: zhpy [-c] source [-e] [encoding] [-v] convertor usage: zhpy [--tw | --cn] input.py [-v] :: $ zhpy --tw input.py [-v] $ zhpy --cn input.py [-v] """ argv = sys.argv[1:] os.chdir(os.getcwd()) source = None target = None encoding = None raw_source = None verbose = False python = False tw = False cn = False NonEnglish = False # run as interpreter if len(argv) == 0: from interpreter import interpreter import import_hook display = os.getenv("LANG") if display == None: interpreter() elif "zh_TW" in display: interpreter('tw') elif "zh_CN" in display: interpreter('cn') else: interpreter() sys.exit() # run as script # not accept any option elif not argv[0].startswith('-'): source = argv[0] sys.argv = argv # run as command elif len(argv)==1: if argv[0] == '--info': from info import info info() sys.exit() if argv[0] == '-V' or argv[0] == '--version': from release import version print "zhpy %s on python %s"%(version, sys.version.split()[0]) sys.exit() elif argv[0] == '-h' or argv[0] == '--help': print commandline.__doc__ sys.exit() # run as native interpreter elif argv[0] == '--tw': from interpreter import interpreter import import_hook interpreter('tw') sys.exit() elif argv[0] == '--cn': from interpreter import interpreter import import_hook interpreter('cn') sys.exit() else: print commandline.__doc__ sys.exit() # accept "-c -e -v" elif len(argv)>=2: if argv[0] == '-c' or argv[0] == '--cmp': raw_source = argv[1] del(argv[:2]) if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or \ argv[0] == '--verbose'): verbose = True # python to twpy elif argv[0] == '--tw': from pyzh import zh_chr, rev_annotator rev_annotator() source = argv[1] filename = os.path.splitext(source)[0] # remove extra .tw in filename profix = os.path.splitext(filename)[-1] if profix =='.tw': filename = os.path.splitext(filename)[0] del(argv[:2]) tw = True target = "v_"+zh_chr(filename)+".twpy" if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True # python to cnpy elif argv[0] == '--cn': from pyzh import zh_chr, rev_annotator rev_annotator() source = argv[1] filename = os.path.splitext(source)[0] # remove extra .cn in filename profix = os.path.splitext(filename)[-1] if profix == '.cn': filename = os.path.splitext(filename)[0] del(argv[:2]) cn = True target = "v_"+zh_chr(filename)+".cnpy" if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True # accept "-i -o -e -v" or "-p -e" or "-c -e -v" elif argv[0] == '-i' or argv[0] == '--input': source = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or \ argv[0] == '--verbose'): verbose = True if len(argv)>=2 and (argv[0] == '-o' or argv[0] == '--output'): target = argv[1] del(argv[:2]) if len(argv)>=2 and (argv[0] == '-e' or \ argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or \ argv[0] == '--verbose'): verbose = True elif argv[0] == '-p' or argv[0] == '--python': source = argv[1] filename = os.path.splitext(source)[0] # remove extra .tw in filename profix = os.path.splitext(filename)[-1] if (profix =='.tw') or (profix =='.cn'): filename = os.path.splitext(filename)[0] del(argv[:2]) # chinese filename to uri filename for i in filename: if i not in \ list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.'): NonEnglish = True print i, "file name is not in english" break if NonEnglish: target = zh_ord(filename.decode('utf8'))+".py" print "compile to python and run: %s"%( zh_ord(filename.decode('utf8'))+".py") else: target = "n_"+filename+".py" print "compile to python and run: %s"%("n_"+filename+".py") python = True if (len(argv)!=0) and (argv[0] == '-v' or argv[0] == '--verbose'): verbose = True if len(argv)>=2 and (argv[0] == '-e' or argv[0] == '--encoding'): encoding = argv[1] del(argv[:2]) if (len(argv)!=0) and (argv[0] == '-v' or \ argv[0] == '--verbose'): verbose = True else: print commandline.__doc__ sys.exit() #convert if raw_source: if verbose: print "run raw_source", raw_source #annotator() if encoding: result = convertor(raw_source, verbose, encoding) else: result = convertor(raw_source, verbose) zh_exec(result) import import_hook sys.exit() if encoding: print "encoding", encoding if source: if verbose: print "input", source # convertor if(tw or cn): if verbose: print "convert python code to", try: from pyzh import rev_annotator, python_convertor test = file(source, "r").read() if tw: print "twpy" rev_annotator('tw', verbose) result = python_convertor(test, lang='tw') if cn: print "cnpy" rev_annotator('cn', verbose) result = python_convertor(test, lang='cn') except Exception, e: print "zhpy Exception: you may input unproper source" if verbose: print e sys.exit() else: try: test = file(source, "r").read() #annotator() import import_hook if encoding: result = convertor(test, verbose, encoding) else: result = convertor(test, verbose) except Exception, e: print "zhpy Exception: you may input unproper source" if verbose: print e sys.exit()