Exemple #1
0
 def writeBlock(self, words, addr):
     if addr < 0x100:
         lib.error("Error: Runtime Error: Invalid instruction address")
     addr = addr - 0x100
     addr = addr / 4
     for i in range(4):
         self.__data[addr] = words[i]
         addr += 1
Exemple #2
0
def fh(path):
    if path in opened: return opened[path]
    try:
        f = open(path, "a")
        opened[path] = f
        return f
    except:
        error("指定したパスには書き込みできません: " + path)
Exemple #3
0
 def start(self):
     global o, e
     s = type(self.args) is str
     try:
         self.popen = subprocess.Popen(self.args,
                                       shell=s,
                                       stdout=o,
                                       stderr=e)
         self.pid = self.popen.pid
     except:
         error(f"実行に失敗しました: {self.description}")
Exemple #4
0
def port_scan(ip, filename):
    """
    nmap scann
    """
    try:
        green(f'Run cmd -> {cmd2.format(ip,libs.root,filename)}')
        libs.commands_(cmd=[cmd2.format(ip, libs.root, filename)])
        time.sleep(10)
        data1 = libs.commands_(cmd=[
            'sudo python2 {}lib/nmap_xml.py {}lib/nmap_xml/{}'.format(
                libs.root, libs.root, filename)
        ]).strip()
        # data1 = exec('data1 = '+data1)
        data1 = eval(data1)
        foo.nScan_Result = data1
        for i in range(0, 2):
            for d1 in foo.nScan_Result[i]:
                if 'ip' in d1 and \
                    'port' in d1 and \
                    'state' in d1 and \
                    'agreement' in d1:

                    ip = d1.get('ip')
                    port = d1.get('port')
                    state = d1.get('state')
                    agreement = d1.get('agreement')

                    if ip:
                        print('')
                        if state != 'closed' and state != 'filtered':
                            info(ip + ':' + port + ' /' + state + ' ' + '-' +
                                 agreement)
                            if port == '443' or port == '80':
                                w = open(
                                    '{}lib/Nmap_Result/nScan_Result.txt'.
                                    format(libs.root), 'a+')
                                w.write(
                                    '{"ip":"%s","port":"%s","state":"%s","agreement":"%s"}'
                                    % (ip, port, state, agreement))
                                w.write('\n')
                                warning('写入 lib/batch/nScan_Result.txt ...')
                                w.close()

                        else:
                            if state == 'closed':
                                error(ip + ':' + port + ' /' + state + ' ' +
                                      '-' + agreement)
                            elif state == 'filtered':
                                warning(ip + ':' + port + ' /' + state + ' ' +
                                        '-' + agreement)

    except Exception as e:
        # error(traceback.format_exc())
        pass
Exemple #5
0
def create_ring(roi_name, r2, r1=0, new_name=None):
    """
    Creates a ring ROI around another source ROI.  The ring is specified by two
    distance parameters, :math:`r_1` and :math:`r_2`.  A ring of uniform thickness
    is assumed.

    - By default, :math:`r_1`, the inward distance, is set at 0, which makes the ring ROI inner surface coincide with the source roi surface.
    - The outward distance, :math:`r_2`, must always be specified.  It corresponds to the outward distance from the source ROI surface.  If set at zero, the outer surface of the ring ROI will correspond to the source ROI surface.
    - The sum :math:`r_1 + r_2` therefore gives the ring thickness.

    Args:
        r2 (float): the outward distance in cm
        r1 (float, optional): the inward distance in cm (default 0)
        new_name (str, optional): the name of the newly created ring ROI.  If unspecified, the name will automatically be generated based on *r2* and *r1*.

    Returns:
        the ROI RayStation object corresponding to the new ring ROI
    """
    if r1 < 0 or r2 < 0:
        lib.error('Cannot have a negative distance.')

    if new_name is None:
        if r1 == 0:
            new_name = "%s_ring_%dmm" % (roi_name, r2 * 10)
        else:
            new_name = "%s_ring_%d-%dmm" % (roi_name, r1 * 10, r2 * 10)
    patient = lib.get_current_patient()
    examination = lib.get_current_examination()
    source_roi = get_roi(roi_name)
    # with CompositeAction('ROI Algebra (%s)' % roi_name):
    #     ring_roi = patient.PatientModel.CreateRoi(Name=new_name, Type="Organ", TissueName=None, RoiMaterial=None)
    #     ring_roi.SetRoiMaterial(Material=source_roi.RoiMaterial)
    #     ring_roi.SetAlgebraExpression(ExpressionA=dict(Operation="Union", SourceRoiNames=[roi_name], MarginSettings=get_margin_settings(r2)),
    #                                   ExpressionB=dict(Operation="Union", SourceRoiNames=[roi_name], MarginSettings=get_margin_settings(r1)),
    #                                   ResultOperation="Subtraction",
    #                                   ResultMarginSettings=get_margin_settings(0))
    #     ring_roi.UpdateDerivedGeometry(Examination=examination)
    with CompositeAction('Create Wall (%s, Image set: %s)' %
                         (roi_name, examination)):
        ring_roi = patient.PatientModel.CreateRoi(Name=new_name,
                                                  Color="White",
                                                  Type="Organ",
                                                  TissueName=None,
                                                  RoiMaterial=None)
        ring_roi.SetRoiMaterial(Material=source_roi.OfRoi.RoiMaterial)
        ring_roi.SetWallExpression(SourceRoiName=roi_name,
                                   OutwardDistance=r2,
                                   InwardDistance=r1)
        ring_roi.UpdateDerivedGeometry(Examination=examination)
    return ring_roi
Exemple #6
0
	def add_(self):
    		#添加扫描对象
		try:
			# target = input(self.O+'[Awvs_Api/Set_Target]>> '+self.W)
			target = self.target
			if target:
				data = {'address':target,'description':'','criticality':10}
				r = requests.post(url=self.server+'/targets', timeout=10, 
					verify=False, headers=self.header, data=json.dumps(data))
				if r.status_code == 201:
					return json.loads(r.text)['target_id']
			else:
				return False
		except Exception as e:
			error(e)
Exemple #7
0
def thread():
    pl = SP.multiple(d.command)
    tl = [threading.Thread(target=lambda p: p.run(), args=(p, )) for p in pl]

    try:
        st = now()
        for t in tl:
            t.start()
        for t in tl:
            t.join()
        en = now()
    except:
        error("実行に失敗しました")

    SP.collect(pl, st, en)
Exemple #8
0
    def fetch_inst_block(self, addr):
        if addr < 0x0 or addr >= 0x100:
            lib.error("Error: Runtime Error: Invalid instruction address")
        words = []
        addr = addr / 4

        if addr >= len(self.__inst):
            return None

        for _ in range(4):
            if addr < len(self.__inst):
                words.append(self.__inst[addr])
            else:
                words.append(None)
            addr += 1
        return words
Exemple #9
0
def do_status(args, client, sl_storage, configuration):
    containername = args['<clustername>']
    if containername in clusters(sl_storage):

        vs_manager = SoftLayer.VSManager(client)
        resources = get_resources(sl_storage, containername)
        if 'score' in resources:
            del resources['score']

        if args['<resourcename>']:
            resourcename = args['<resourcename>']
            filteredresources = {}
            status_serverinstances(resources, resourcename,
                                   filteredresources, vs_manager, client)
            resources = filteredresources
        print json.dumps(resources, indent=4, sort_keys=True)
    else:
        error('cluster does not exist')
Exemple #10
0
    def Login_Google_CRX(self):
        try:
            self.browser.get(self.login_url)
            self.browser.minimize_window()
            email = username
            password = passwd
            time.sleep(10)
            log_email = self.browser.find_element_by_id('email').send_keys(
                email)
            log_password = self.browser.find_element_by_id(
                'password').send_keys(password)
            log_password = self.browser.find_element_by_id(
                'password').send_keys(Keys.ENTER)
            info('登入成功...')

        except Exception as e:
            error(('Login_Google_CRX = ', traceback.format_exc()))
            pass
Exemple #11
0
def do_status(args, client, sl_storage, configuration):
    containername = args['<clustername>']
    if containername in clusters(sl_storage):

        vs_manager = SoftLayer.VSManager(client)
        resources = get_resources(sl_storage, containername)
        if 'score' in resources:
            del resources['score']

        if args['<resourcename>']:
            resourcename = args['<resourcename>']
            filteredresources = {}
            status_serverinstances(resources, resourcename, filteredresources,
                                   vs_manager, client)
            resources = filteredresources
        print json.dumps(resources, indent=4, sort_keys=True)
    else:
        error('cluster does not exist')
Exemple #12
0
    def __init__(self, cfgfile_name=None, handler=sys.stdout, terminal=True):
        self.handler = handler
        self.terminal = terminal
        self.category_names = CATEGORY_NAMES_DEFAULT

        if cfgfile_name is not None:
            try:
                config_file = open(cfgfile_name)
                config = toml.loads(config_file.read())
                self.category_names = config.get('category_names', None)
            except IOError as e:
                lib.error("Configuration: %s" % e,
                              self.handler, terminal=self.terminal)
                lib.warning("No Valid Configuration file! Use Default",
                                self.handler, terminal=self.terminal)

        if self.category_names is None:
            lib.warning("No Valid Configuration file! Use Default",
                            self.handler, terminal=self.terminal)
Exemple #13
0
def main():
    args = docopt(__doc__, version='kleiber cluster director  0.1')
    try:
        configuration = yaml.load(
            open(os.environ['HOME'] + '/.kleiber', 'r').read())
    except IOError:
        error('kleiber configuration file {} not found'.format(
            os.environ['HOME'] + '/.kleiber'))

    client = SoftLayer.create_client_from_env(
        username=configuration['username'], api_key=configuration['api_key'])

    if 'obj_store' not in configuration:
        if 'local_store' in configuration:
            directory = configuration['local_store']
        else:
            directory = os.path.expanduser("~/.kleiber-data")
        sl_storage = {
            'type': 'local',
            'directory': os.path.expanduser(directory + "/containers/")
        }
    else:
        sl_storage = {
            'type':
            'swift',
            'client':
            object_storage.get_client(
                configuration['obj_store']['name'] + ':' +
                configuration['username'],
                configuration['api_key'],
                datacenter=configuration['obj_store']['datacenter'])
        }

    if args['create']:
        do_create(args, client, sl_storage, configuration)
    elif args['status']:
        do_status(args, client, sl_storage, configuration)
    elif args['delete']:
        do_delete(args, client, sl_storage, configuration)
    elif args['list']:
        print clusters(sl_storage)
Exemple #14
0
def main():
    args = docopt(__doc__, version='kleiber cluster director  0.1')
    try:
        configuration = yaml.load(
                open(os.environ['HOME']+'/.kleiber', 'r').read())
    except IOError:
        error('kleiber configuration file {} not found'.format(
                    os.environ['HOME']+'/.kleiber'))

    client = SoftLayer.create_client_from_env(
                          username=configuration['username'],
                          api_key=configuration['api_key'])

    if 'obj_store' not in configuration:
        if 'local_store' in configuration:
            directory = configuration['local_store']
        else:
            directory = os.path.expanduser("~/.kleiber-data")
        sl_storage = {
            'type': 'local',
            'directory': os.path.expanduser(directory+"/containers/")
        }
    else:
        sl_storage = {
            'type': 'swift',
            'client': object_storage.get_client(
              configuration['obj_store']['name']+':'+configuration['username'],
              configuration['api_key'],
              datacenter=configuration['obj_store']['datacenter'])
        }

    if args['create']:
        do_create(args, client, sl_storage, configuration)
    elif args['status']:
        do_status(args, client, sl_storage, configuration)
    elif args['delete']:
        do_delete(args, client, sl_storage, configuration)
    elif args['list']:
        print clusters(sl_storage)
Exemple #15
0
def do_create(args, client, sl_storage, configuration):

    if args['-v']:
        DebugLevel.set_level('verbose')
    else:
        DebugLevel.set_level('progress')

    containername = args['<clustername>']
    if args['<clustername>'] in clusters(sl_storage):
        error('cluster {} already exists'.format(args['<clustername>']))

    scoretext = open(args['<score.yaml>'], 'r').read()
    score = yaml.load(scoretext)

    score['clustername'] = args['<clustername>']
    dirname = os.path.dirname(args['<score.yaml>'])
    if dirname == "":
        dirname = "."
    score['path'] = dirname+"/"

    # setup environment for scripts in score to run properly. Change to
    #  the score directory and add . to the path
    os.chdir(score['path'])
    os.environ['PATH'] = ':'.join([os.environ['PATH'], './'])

    if 'parameters' in score:
        parmvalues = score['parameters']
    else:
        parmvalues = {}

    parameters = args['<key=value>']
    for param in parameters:
        splits = param.split('=', 1)
        if len(splits) != 2:
            raise Exception("{} is not a key=value pair".format(param))
        parmvalues[splits[0]] = splits[1]
    score['parameters'] = parmvalues
    scoretext = yaml.dump(score, indent=4)

    msg = validate_provision_parms_passed(scoretext, parmvalues)
    debug(msg)
    if msg:
        error(msg)

    state_container_create(sl_storage, containername)
    try:
        # save score for later operations
        save_state(sl_storage, containername, 'score', scoretext)
        provision(args['<clustername>'], containername, score,
                  configuration, client, sl_storage)
    except Exception, e:
        debug(traceback.format_exc())
        resources = get_resources(sl_storage, containername)
        del resources['score']
        if deletable(resources):
            state_container_clean(sl_storage, containername)
        error(e.message)
Exemple #16
0
def do_create(args, client, sl_storage, configuration):

    if args['-v']:
        DebugLevel.set_level('verbose')
    else:
        DebugLevel.set_level('progress')

    containername = args['<clustername>']
    if args['<clustername>'] in clusters(sl_storage):
        error('cluster {} already exists'.format(args['<clustername>']))

    scoretext = open(args['<score.yaml>'], 'r').read()
    score = yaml.load(scoretext)

    score['clustername'] = args['<clustername>']
    dirname = os.path.dirname(args['<score.yaml>'])
    if dirname == "":
        dirname = "."
    score['path'] = dirname + "/"

    # setup environment for scripts in score to run properly. Change to
    #  the score directory and add . to the path
    os.chdir(score['path'])
    os.environ['PATH'] = ':'.join([os.environ['PATH'], './'])

    if 'parameters' in score:
        parmvalues = score['parameters']
    else:
        parmvalues = {}

    parameters = args['<key=value>']
    for param in parameters:
        splits = param.split('=', 1)
        if len(splits) != 2:
            raise Exception("{} is not a key=value pair".format(param))
        parmvalues[splits[0]] = splits[1]
    score['parameters'] = parmvalues
    scoretext = yaml.dump(score, indent=4)

    msg = validate_provision_parms_passed(scoretext, parmvalues)
    debug(msg)
    if msg:
        error(msg)

    state_container_create(sl_storage, containername)
    try:
        # save score for later operations
        save_state(sl_storage, containername, 'score', scoretext)
        provision(args['<clustername>'], containername, score, configuration,
                  client, sl_storage)
    except Exception, e:
        debug(traceback.format_exc())
        resources = get_resources(sl_storage, containername)
        del resources['score']
        if deletable(resources):
            state_container_clean(sl_storage, containername)
        error(e.message)
def get_poi(poi_name, examination=None):
    """
    Returns POI object from a POI name.

    Args:
        poi_name (str): the name of the POI
        examination (str, optional): the name of the examination (CT or StructureSet) for which the poi is defined; if left out the currently selected examination is used.

    Returns:
        the RayStation POI object
    """
    patient = lib.get_current_patient()

    if examination is None:
        examination = lib.get_current_examination()

    try:
        poi = [
            x for x in patient.PatientModel.StructureSets[
                examination.Name].PoiGeometries if x.OfPoi.Name == poi_name
        ][0]

        if abs(poi.Point.x) == sys.float_info.max or abs(
                poi.Point.x) == sys.float_info.min:
            lib.error(
                'POI %s is not segmented on current examination.  Select correct CT and try again.'
                % poi_name)

        return poi
    except IndexError as e:
        logger.error('No POI found named %s', poi_name)
        logger.exception(e)
        raise
    except Exception as e:
        logger.exception(e)
        raise
Exemple #18
0
def get_roi(roi_name, examination=None):
    """
    Returns ROI object from an ROI name for the current structure set.

    Args:
        roi_name (str): the name of the ROI to be returned
        examination (RayStation object, optional): the RayStation object representing the examination

    Returns:
        The ROI RayStation object.
    """
    patient = lib.get_current_patient()

    if examination is None:
        exam = lib.get_current_examination()
    else:
        exam = examination

    try:
        roi = patient.PatientModel.StructureSets[
            exam.Name].RoiGeometries[roi_name]
        if roi.PrimaryShape is None:
            lib.error(
                'ROI %s is not segmented on currently selected examination.  Select correct CT and try again.'
                % roi_name)
    except Exception as e:
        logger.exception(e)
        raise

    # Could have returned roi.OfRoi, but returning roi lets once access the
    # DicomImportHistory, PrimaryShape and GetCenterOfRoi() and GetRoiVolume()
    # functions.
    #
    # Under roi.OfRoi, we have among others Name, Type, Color, RoiMaterial and
    # several functions.  Launch StateTree to see.
    return roi
def argAnalyze(d: data):
    l = argv[1:]

    if len(l) == 0: error("引数が不足しています")
    elif eq(l[0], "-h", "help", "-help", "--help"):
        d.mode = CM.help
        return
    elif eq(l[0], "-v", "version", "-version", "--version"):
        d.mode = CM.version
        return

    key = Key.null
    n = -1
    for a in l:
        n += 1
        if a == "": continue

        proceed = True
        if eq(a, "-m", "-multiple"):
            d.multiple = MM.serial
            key = Key.multiple
        elif eq(a, "-o", "-our", "-stdout"):
            key = Key.out
        elif eq(a, "-e", "-err", "-stderr"):
            key = Key.err
        elif eq(a, "-r", "-result"):
            key = Key.result
        elif a[0] == "-":
            error("不正なオプションが指定されています")
        else:
            proceed = False
        if proceed: continue

        if key != Key.null:
            proceed = True
            if key == Key.out: d.out = a
            if key == Key.err: d.err = a
            if key == Key.result: d.result = a
            if key == Key.multiple:
                if eq(a, "none"): d.multiple = MM.none
                elif eq(a, "serial", ""): d.multiple = MM.serial
                elif eq(a, "spawn", "parallel"): d.multiple = MM.spawn
                elif eq(a, "thread"): d.multiple = MM.thread
                else: proceed = False
            key = Key.null
        if proceed: continue

        d.command = l[n:len(l)]
        break

    if len(d.command) == 0: error("実行する内容が指定されていません")
Exemple #20
0
    def start(self):
        """Start software by checking required files and directry."""

        # Check user home directory
        if not self._home_dir:
            lib.error("User doesn't have home directory!")
            lib.exit_software(1)

        # Check project directory
        if not lib.is_exists(self._home_dir, self._project_dir):
            if not lib.create_dir(self._home_dir, self._project_dir):
                lib.error(
                    "Couldn't create project directory in your home({}) directory."
                    .format(self._home_dir))
                lib.exit_software(1)

        project_dir = lib.join_path(self._home_dir, self._project_dir)

        # Check config file
        if not lib.is_exists(project_dir, self._files["config"]):
            if not lib.create_file_with_content(project_dir,
                                                self._files["config"],
                                                "style=default\ndark=false"):
                lib.error(
                    "Could'nt create config file in the project({}) directory."
                    .format(project_dir))
                lib.exit_software(1)

        # Check database file
        if not lib.is_exists(project_dir, self._files["database"]):
            if not lib.create_empty_db_file(project_dir,
                                            self._files["database"]):
                lib.error(
                    "Couldn't create empty database in the project({}) directory."
                    .format(project))
                lib.exit_software(1)
Exemple #21
0
    async def on_command_error(self, context, error):
        """
        Method to run if there is an exception thrown by a command
        :param error:
        :param context:
        :return:
        """

        ignore = (commands.errors.CommandNotFound,
                  commands.errors.UserInputError)

        if isinstance(error, ignore):
            return
        elif isinstance(error, commands.errors.NoPrivateMessage):
            return await context.send(
                'Commands cannot be used in Private Messages.')
        elif isinstance(error, commands.errors.MissingPermissions):
            user = User(context.message.author.id, context.guild.id, context)
            return await context.send(user.get_mention() + ', ' + str(error))
        elif isinstance(error, commands.errors.CommandInvokeError):
            code = lib.error('CommandInvokeError in command `{}`: {}'.format(
                context.command, str(error)))
            lib.error(
                traceback.format_exception(type(error), error,
                                           error.__traceback__), code)
            user = User(context.message.author.id, context.guild.id, context)
            return await context.send(
                lib.get_string('err:commandinvoke',
                               user.get_guild()).format(code))
        else:
            code = lib.error('Exception in command `{}`: {}'.format(
                context.command, str(error)))
            lib.error(
                traceback.format_exception(type(error), error,
                                           error.__traceback__), code)
            user = User(context.message.author.id, context.guild.id, context)
            return await context.send(
                lib.get_string('err:unknown', user.get_guild()).format(code))
Exemple #22
0
    def decode(self, inst):
        if inst is not None:
            self._slot.addinst(inst)
            inst_s = inst.getInst()
            idx = inst_s.find(":")
            if idx != -1:
                inst_s = inst_s[idx + 1:]
            inst_s = inst_s.strip()
            idx = inst_s.find(" ")
            itype = inst_s
            if idx > 0:
                itype = inst_s[0:idx]

            # decode the instruction
            if itype == "dadd" or itype == "dsub" or itype == "and" or itype == "or":
                components = inst_s[idx:]
                components = components.split(",")
                if len(components) != 3:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                for i in range(len(components)):
                    components[i] = components[i].strip()
                    if components[i][0] != 'r' or int(
                            components[i][1:]) < 0 or int(
                                components[i][1:]) > 31:
                        lib.error("Error: Invalid instruction [Line " +
                                  str(inst.getLine()) + "]")
                rd = int(components[0][1:])
                rs = int(components[1][1:])
                rt = int(components[2][1:])
                inst.setattrs(itype, rs, rt, rd, None, 'r')

            elif itype == "daddi" or itype == "dsubi" or itype == "andi" or itype == "ori":
                components = inst_s[idx:]
                components = components.split(",")
                if len(components) != 3:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                for i in range(len(components) - 1):
                    components[i] = components[i].strip()
                    if components[i][0] != 'r' or int(
                            components[i][1:]) < 0 or int(
                                components[i][1:]) > 31:
                        lib.error("Error: Invalid instruction [Line " +
                                  str(inst.getLine()) + "]")
                rd = int(components[0][1:])
                rs = int(components[1][1:])
                try:
                    imd = int(components[2])
                except:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")
                inst.setattrs(itype, rs, None, rd, imd, 'r')

            elif itype == "add.d" or itype == "div.d" or itype == "sub.d" or itype == "mul.d":
                components = inst_s[idx:]
                components = components.split(",")
                if len(components) != 3:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                for i in range(len(components)):
                    components[i] = components[i].strip()
                    if components[i][0] != 'f' or int(
                            components[i][1:]) < 0 or int(
                                components[i][1:]) > 31:
                        lib.error("Error: Invalid instruction [Line " +
                                  str(inst.getLine()) + "]")
                rd = int(components[0][1:])
                rs = int(components[1][1:])
                rt = int(components[2][1:])
                inst.setattrs(itype, rs, rt, rd, None, 'f')

            elif itype == "lw":
                components = inst_s[idx:]
                components = components.split(",")

                if len(components) != 2:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                for i in range(len(components)):
                    components[i] = components[i].strip()

                if components[0][0] != "r" or int(
                        components[0][1:]) < 0 or int(components[0][1:]) > 31:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                try:
                    idx = components[1].find("(")
                    imd = int(components[1][:idx])
                    coms = components[1][idx:][1:-1]
                    if coms[0] != "r" or int(coms[1:]) < 0 or int(
                            coms[1:]) > 31:
                        lib.error("Error: Invalid instruction [Line " +
                                  str(inst.getLine()) + "]")
                    inst.setattrs(itype, int(coms[1:]), None,
                                  int(components[0][1:]), imd, 'r')
                except:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

            elif itype == "sw":
                components = inst_s[idx:]
                components = components.split(",")
                if len(components) != 2:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                for i in range(len(components)):
                    components[i] = components[i].strip()

                if components[0][0] != "r" or int(
                        components[0][1:]) < 0 or int(components[0][1:]) > 31:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                try:
                    idx = components[1].find("(")
                    imd = int(components[1][:idx])
                    coms = components[1][idx:][1:-1]
                    if coms[0] != "r" or int(coms[1:]) < 0 or int(
                            coms[1:]) > 31:
                        lib.error("Error: Invalid instruction [Line " +
                                  str(inst.getLine()) + "]")
                    inst.setattrs(itype, int(coms[1:]), int(components[0][1:]),
                                  None, imd, 'r')
                except:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")
            elif itype == "l.d":
                components = inst_s[idx:]
                components = components.split(",")
                if len(components) != 2:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                for i in range(len(components)):
                    components[i] = components[i].strip()

                if components[0][0] != "f" or int(
                        components[0][1:]) < 0 or int(components[0][1:]) > 31:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                try:
                    idx = components[1].find("(")
                    imd = int(components[1][:idx])
                    coms = components[1][idx:][1:-1]
                    if coms[0] != "r" or int(coms[1:]) < 0 or int(
                            coms[1:]) > 31:
                        lib.error("Error: Invalid instruction [Line " +
                                  str(inst.getLine()) + "]")
                    inst.setattrs(itype, int(coms[1:]), None,
                                  int(components[0][1:]), imd, 'f')
                except:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")
            elif itype == "s.d":
                components = inst_s[idx:]
                components = components.split(",")
                if len(components) != 2:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                for i in range(len(components)):
                    components[i] = components[i].strip()

                if components[0][0] != "f" or int(
                        components[0][1:]) < 0 or int(components[0][1:]) > 31:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                try:
                    idx = components[1].find("(")
                    imd = int(components[1][:idx])
                    coms = components[1][idx:][1:-1]
                    if coms[0] != "r" or int(coms[1:]) < 0 or int(
                            coms[1:]) > 31:
                        lib.error("Error: Invalid instruction [Line " +
                                  str(inst.getLine()) + "]")
                    inst.setattrs(itype, int(coms[1:]), int(components[0][1:]),
                                  None, imd, 'f')
                except:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

            elif itype == "bne" or itype == "beq":
                components = inst_s[idx:]
                components = components.split(",")
                if len(components) != 3:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")

                for i in range(len(components) - 1):
                    components[i] = components[i].strip()
                    if components[i][0] != 'r' or int(
                            components[i][1:]) < 0 or int(
                                components[i][1:]) > 31:
                        lib.error("Error: Invalid instruction [Line " +
                                  str(inst.getLine()) + "]")
                rs = int(components[0][1:])
                rt = int(components[1][1:])
                try:
                    imd = self.__table[components[2]]
                except:
                    lib.error(
                        "Error: Invalid instruction: missing label [Line " +
                        str(inst.getLine()) + "]")
                inst.setattrs(itype, rs, rt, None, imd, 'j')

            elif itype == "j":
                components = inst_s[idx:].strip()
                try:
                    imd = self.__table[components]
                except:
                    lib.error("Error: Invalid instruction [Line " +
                              str(inst.getLine()) + "]")
                inst.setattrs(itype, None, None, None, imd, 'j')

            elif itype == "hlt":
                inst.setattrs(itype, None, None, None, None, 'h')

            else:
                lib.error("Error: Unknown instruction [Line " +
                          str(inst.getLine()) + "]")

            inst.setdecoded()
            inst.markunready()

        # check WAW hazard
        if not self._slot.empty():
            inst = self._slot.getinst()
            if not inst.WAWchecked():
                attrs = inst.getattrs()
                if attrs[5] == 'r':
                    if attrs[3] is not None:
                        if self.__Rs[attrs[3]] == None:
                            self.__Rs[attrs[3]] = inst
                            inst.setWAW()
                        else:
                            inst.WAW()
                    else:
                        inst.setWAW()
                elif attrs[5] == "f":
                    if attrs[3] is not None:
                        if self.__Fs[attrs[3]] == None:
                            self.__Fs[attrs[3]] = inst
                            inst.setWAW()
                        else:
                            inst.WAW()
                    else:
                        inst.setWAW()
                else:
                    inst.setWAW()

        # check RAW hazard
        if not self._slot.empty():
            inst = self._slot.getinst()
            attrs = inst.getattrs()
            if attrs[5] == "r":
                allset = True
                # read rs
                if attrs[1] is not None:
                    # RAW hazard
                    if self.__Rs[attrs[1]] is not None and self.__Rs[
                            attrs[1]] != inst:
                        allset = False
                    else:
                        inst.setrs(self.__regfile.getword(attrs[1]))

                if attrs[2] is not None:
                    # RAW hazard
                    if self.__Rs[attrs[2]] is not None and self.__Rs[
                            attrs[2]] != inst:
                        allset = False
                    else:
                        inst.setrt(self.__regfile.getword(attrs[2]))

                if allset:
                    inst.setRAW()
                else:
                    inst.RAW()

            elif attrs[5] == "f":
                if attrs[0] == "l.d":
                    allset = True
                    # read rs
                    if attrs[1] is not None:
                        # RAW hazard
                        if self.__Rs[attrs[1]] is not None and self.__Rs[
                                attrs[1]] != inst:
                            allset = False
                        else:
                            inst.setrs(self.__regfile.getword(attrs[1]))

                    if allset:
                        inst.setRAW()
                    else:
                        inst.RAW()

                elif attrs[0] == "s.d":
                    allset = True
                    # read rs
                    if attrs[1] is not None:
                        # RAW hazard
                        if self.__Rs[attrs[1]] is not None and self.__Rs[
                                attrs[1]] != inst:
                            allset = False
                        else:
                            inst.setrs(self.__regfile.getword(attrs[1]))

                    if attrs[2] is not None:
                        # RAW hazard
                        if self.__Fs[attrs[2]] is not None and self.__Rs[
                                attrs[2]] != inst:
                            allset = False
                        else:
                            inst.setrt(0)

                    if allset:
                        inst.setRAW()
                    else:
                        inst.RAW()

                else:
                    allset = True
                    # read rs
                    if attrs[1] is not None:
                        # RAW hazard
                        if self.__Fs[attrs[1]] is not None and self.__Fs[
                                attrs[1]] != inst:
                            allset = False
                        else:
                            inst.setrs(0)

                    if attrs[2] is not None:
                        # RAW hazard
                        if self.__Fs[attrs[2]] is not None and self.__Fs[
                                attrs[2]] != inst:
                            allset = False
                        else:
                            inst.setrt(0)

                    if allset:
                        inst.setRAW()
                    else:
                        inst.RAW()

            elif attrs[5] == "j":
                itype = attrs[0]
                if itype == "bne" or itype == "beq":
                    allset = True
                    # read rs
                    if attrs[1] is not None:
                        # RAW hazard
                        if self.__Rs[attrs[1]] is not None and self.__Rs[
                                attrs[1]] != inst:
                            allset = False
                        else:
                            inst.setrs(self.__regfile.getword(attrs[1]))

                    if attrs[2] is not None:
                        # RAW hazard
                        if self.__Rs[attrs[2]] is not None and self.__Rs[
                                attrs[2]] != inst:
                            allset = False
                        else:
                            inst.setrt(self.__regfile.getword(attrs[2]))

                    if allset:
                        inst.setRAW()
                    else:
                        inst.RAW()
                else:
                    inst.setRAW()
            else:
                inst.setRAW()

        if not self._slot.empty():
            inst = self._slot.getinst()
            if inst.decoded() and inst.WAWchecked() and inst.RAWchecked():
                inst.markready()
Exemple #23
0
        if param[0] == 'fp adder':
            if len(param[1]) == 2:
                try:
                    cycle = int(param[1][0])
                    if cycle <= 0:
                        raise

                    if param[1][1] == 'yes':
                        fp_adder = func_unit.fp_adder(cycle, True)
                        orderlist.append(("adder", True, cycle))
                    elif param[1][1] == 'no':
                        fp_adder = func_unit.fp_adder(cycle, False)
                        orderlist.append(("adder", False, cycle))
                    else:
                        lib.error(
                            "Error: Invalid config file: invalid or missing attribute [Line "
                            + str(params.index(param) + 1) + "]")
                except:
                    lib.error(
                        "Error: Invalid config file: invalid cycle number [Line "
                        + str(params.index(param) + 1) + "]")
            else:
                lib.error(
                    "Error: Invalid config file: invalid number of attributes [Line "
                    + str(params.index(param) + 1) + "]")
        elif param[0] == 'fp multiplier':
            if len(param[1]) == 2:
                try:
                    cycle = int(param[1][0])
                    if cycle <= 0:
                        raise
def place_prescription_point(target_fraction_dose,
                             ptv_name,
                             poi_name,
                             beamset=None,
                             exam=None):
    """
    Attempts to place automatically a POI on a target per-fraction isodose line.

    .. rubric::
      PRE-REQUISITES

    - Existence of an identifiable PTV contour.
    - Dose is calculated.

    .. rubric::
      Algorithm description

    - A point on the PTV contour on a slice near the PTV center is found.
    - The dose is evaluated at that point.
    - An approximate unit vector towards the PTV center is calculated from that position.
        + If the evaluated dose is smaller than the prescription dose, the evaluation point is moved a short distance towards the PTV center.
        + If the evaluated dose is greater than the prescription dose, the evaluation point is moved a short distance away from the PTV center.
    - If the prescription dose is overshot by this procedure, the direction of movement is reversed and the move distance halved.
    - This process is repeated until evaluated dose equals the prescription dose to 3 decimal figures or 100 iterations are reached.

    Finally,

    - The specified POI is placed at the found coordinates.

    .. seealso::
      function `hmrlib.hmrlib.auto_place_prescription_point`

    """

    patient = lib.get_current_patient()
    if exam is None:
        exam = lib.get_current_examination()

    if beamset is None:
        beamset = lib.get_current_beamset()

    try:
        # Get PTV center
        ptv_center = lib.RSPoint(point=patient.PatientModel.StructureSets[
            exam.Name].RoiGeometries[ptv_name].GetCenterOfRoi())

        # Get slice thickness from CT
        slice_width = abs(exam.Series[0].ImageStack.SlicePositions[1] -
                          exam.Series[0].ImageStack.SlicePositions[0])
        logger.info('CT slice width = %s cm', slice_width)

        initial_point = None
        # Find contour point on a slice close to PTV center
        for c in patient.PatientModel.StructureSets[
                exam.Name].RoiGeometries[ptv_name].PrimaryShape.Contours:
            #if lib.check_version(4.7):
            if c[0].z < ptv_center.z + slice_width and c[
                    0].z > ptv_center.z - slice_width:
                initial_point = lib.RSPoint(c[0].x, c[0].y, c[0].z)
                break
            #else:
            #    if c.ContourData[0].z < ptv_center.z + slice_width and c.ContourData[0].z > ptv_center.z - slice_width:
            #        initial_point = lib.RSPoint(c.ContourData[0].x, c.ContourData[0].y, c.ContourData[0].z)
            #        break

        if initial_point is None:
            logger.info(
                'Could not find a point on the same slice as the ROi center. Disjoint/noncoplanar PTV?'
            )
            logger.info('Trying with first point in contour shape.')
            c = patient.PatientModel.StructureSets[
                exam.Name].RoiGeometries[ptv_name].PrimaryShape.Contours[0]
            #if lib.check_version(4.7):
            initial_point = lib.RSPoint(c[0].x, c[0].y, c[0].z)
            #else:
            #    initial_point = lib.RSPoint(c.ContourData[0].x, c.ContourData[0].y, c.ContourData[0].z)

        logger.info('Initial point = %s cm', initial_point)

        u = lib.RSPoint(point=lib.unit_vector(ptv_center - initial_point))
        logger.info('Unit vector towards PTV center = %s cm', u)

        # Change unit vector so that we stay on the same transverse slice
        u.z = 0
        logger.info(
            'Approximate unit vector towards PTV center on single CT slice = %s cm',
            u)

        def move_point(point,
                       direction,
                       target_fraction_dose,
                       initial_dose,
                       step=0.05,
                       iteration=0):
            point = point + step * direction
            dose = beamset.FractionDose.InterpolateDoseInPoint(
                Point=point.value)
            logger.info('Dose at %s = %.3f cGy', point, dose)
            if round(dose, 3) == round(target_fraction_dose,
                                       3) or iteration > 100:
                # Found a suitable point or reached max iterations
                return point
            elif (initial_dose < target_fraction_dose and dose >
                  target_fraction_dose) or (initial_dose > target_fraction_dose
                                            and dose < target_fraction_dose):
                # We overshot the point, so inverse direction and reduce step
                return move_point(point,
                                  -direction,
                                  target_fraction_dose,
                                  dose,
                                  step=0.5 * step,
                                  iteration=iteration + 1)
            else:
                # Keep going in the same direction with same step
                return move_point(point,
                                  direction,
                                  target_fraction_dose,
                                  dose,
                                  step=step,
                                  iteration=iteration + 1)

        dose = beamset.FractionDose.InterpolateDoseInPoint(
            Point=initial_point.value)

        if math.isnan(dose):
            lib.error('No dose value available.  Check if dose is calculated.')

        logger.info('Dose per fraction at initial point = %.3f cGy', dose)

        # Assume dose rises when moving towards center of PTV
        if dose < target_fraction_dose:
            point = move_point(initial_point, u, target_fraction_dose, dose)
        else:
            point = move_point(initial_point, -u, target_fraction_dose, dose)

        logger.info('Final point = %s cm', point)

    except Exception as e:
        logger.exception(e)
        raise

    if get_poi_approval(poi_name):
        logger.warning('POI %s is approved; cannot continue.', poi_name)
        lib.error(
            'POI %s exists and is approved; cannot continue.  Unapprove %s before running script.'
            % (poi_name, poi_name))

    set_poi_coordinates(poi_name, point, examination=exam)

    return point
Exemple #25
0
def set_optimization_parameters(fluence_iterations=60, max_iterations=100, optimality_tolerance=1E-09, compute_intermediate_dose=True, compute_final_dose=True, plan=None, beamset=None):
    """
    Sets the optimization parameters for inverse planning.

    **RESETS OPTIMIZATION IF ALREADY STARTED**

    Args:
        fluence_iterations (int, optional): the number of fluence iterations (default: 60)
        max_iterations (int, optional): the maximum number of iterations (default: 100)
        optimality_tolerance (float, optional): the tolerance of the optimizer such that it has reached an optimal solution with respect to the objective value (default: 1E-9)
        compute_intermediate_dose (bool, optional): whether of not to compute clinical dose after completing fluence iterations.  This dose is taken into account in the following optimization iterations (default: True).
        compute_final_dose (bool, optional): whether or not to compute clinical dose after optimization is done (default: True)
        plan (RS Object, optional): the RayStation plan object (if none specified, will get current)
        beamset (str or int, optional): the name of the beamset to modify.  If not used, all beamsets in the plan are affected.  An int can be provided as well (1 for first beamset, 2 for second beamset, etc.).
    """
    if plan is None:
        plan = lib.get_current_plan()

    if fluence_iterations > max_iterations:
        lib.error('Fluence iterations cannot be greater than the maximum number of iterations.')

    if beamset is None:
        logger.info('No beamset specified.  All beamsets will be modified.')
        l = 0
        for po in plan.PlanOptimizations:
            l += 1
        indices = range(l)
    elif isinstance(beamset, str):
        # figure out what index of PlanOptimizations is this beamset
        i = 0
        for po in plan.PlanOptimizations:
            for obs in po.OptimizedBeamSets:
                if beamset.startswith(obs.DicomPlanLabel):
                    break
            break
            i += 1

        indices = [i]
    elif isinstance(beamset, int):
        try:
            indices = [beamset - 1]
            test = plan.PlanOptimizations[beamset - 1]
        except IndexError as e:
            lib.error('The index provided for the beamset argument was out of range. Specify the beamset number in the plan (i.e. 1, 2, ...) or provide the beamset name as a string.')

    # TODO Ask confirmation with yes/no dialog before proceeding.
    try:
        for i in indices:
            #if not plan.PlanOptimizations[i].ProgressOfOptimization is None:
                # Reset optimization because this changes parameters that RS doesn't
                # allow changing without resetting.
                #plan.PlanOptimizations[i].ResetOptimization()
                #logger.info('Optimization was reset.')

            logger.info('PlanOptimizations[%s] selected.', i)

            op = plan.PlanOptimizations[i].OptimizationParameters
            op.DoseCalculation.IterationsInPreparationsPhase = fluence_iterations
            logger.info('Fluence iterations set to %s.', fluence_iterations)

            op.Algorithm.MaxNumberOfIterations = max_iterations
            logger.info('Max iterations set to %s.', max_iterations)

            op.Algorithm.OptimalityTolerance = optimality_tolerance
            logger.info('Optimality tolerance set to %s.', optimality_tolerance)

            op.DoseCalculation.ComputeIntermediateDose = compute_intermediate_dose
            logger.info('Compute intermediate dose set to %s.', compute_intermediate_dose)

            op.DoseCalculation.ComputeFinalDose = compute_final_dose
            logger.info('Compute final dose set to %s.', compute_final_dose)
    except Exception as e:
        logger.exception(e)
        raise
Exemple #26
0
def set_vmat_conversion_parameters(max_leaf_travel_per_degree=0.1, constrain_leaf_motion=True, arc_gantry_spacing=4, max_arc_delivery_time=350.0, plan=None, beamset=None):
    """
    Sets the VMAT conversion parameters.

    **RESETS OPTIMIZATION IF ALREADY STARTED**

    Args:
        max_leaf_travel_per_degree (float, optional): maximum distance a leaf can move in cm per degree of gantry movement (default: 0.1 cm/degree)
        constrain_leaf_motion (bool, optional): whether or not to impose the *max_leaf_travel_per_degree* constraint (default: True)
        arc_gantry_spacing (int, optional): the spacing in degrees between control points of the arc (default: 4 degrees)
        max_arc_delivery_time (float, optional): the maximum are delivery time in seconds (defautl 350.0 s)
        plan (RS object, optional): the RayStation plan object (if none specified, will get current)
        beamset (str or int, optional): the name of the beamset to modify.  If not used, all beamsets in the plan are affected.  An int can be provided as well (1 for first beamset, 2 for second beamset, etc.).
    """

    if plan is None:
        plan = lib.get_current_plan()

    if beamset is None:
        logger.info('No beamset specified.  All beamsets will be modified.')
        l = 0
        for po in plan.PlanOptimizations:
            l += 1
        indices = range(l)
    elif isinstance(beamset, str):
        # figure out what index of PlanOptimizations is this beamset
        i = 0
        for po in plan.PlanOptimizations:
            for obs in po.OptimizedBeamSets:
                if beamset.startswith(obs.DicomPlanLabel):
                    break
            break
            i += 1

        indices = [i]
    elif isinstance(beamset, int):
        try:
            indices = [beamset - 1]
            test = plan.PlanOptimizations[beamset - 1]
        except IndexError as e:
            lib.error('The index provided for the beamset argument was out of range. Specify the beamset number in the plan (i.e. 1, 2, ...) or provide the beamset name as a string.')

    if arc_gantry_spacing not in [2, 3, 4]:
        lib.error('The arc gantry spacing must be of 2, 3 or 4 degrees.')

    try:
        for i in indices:
            if plan.PlanOptimizations[i].ProgressOfOptimization is not None:
                # Reset optimization because this changes parameters that RS doesn't
                # allow changing without resetting.
                plan.PlanOptimizations[i].ResetOptimization()
                logger.info('Optimization reset.')

            po = plan.PlanOptimizations[i]

            logger.info('PlanOptimizations[%s] selected.', i)

            po.OptimizationParameters.SegmentConversion.ArcConversionProperties.MaxLeafTravelDistancePerDegree = max_leaf_travel_per_degree
            logger.info('Max leaf travel per degree set to %s cm/deg.', max_leaf_travel_per_degree)

            po.OptimizationParameters.SegmentConversion.ArcConversionProperties.UseMaxLeafTravelDistancePerDegree = constrain_leaf_motion
            logger.info('Constrain leaf motion set to %s.', constrain_leaf_motion)

            for ts in po.OptimizationParameters.TreatmentSetupSettings:
                for bs in ts.BeamSettings:
                    bs.ArcConversionPropertiesPerBeam.FinalArcGantrySpacing = arc_gantry_spacing
                    logger.info('Arc gantry spacing set to %s degrees for arc "%s".', arc_gantry_spacing, bs.ForBeam.Name)

                    bs.ArcConversionPropertiesPerBeam.MaxArcDeliveryTime = max_arc_delivery_time
                    logger.info('Max arc delivery time set to %s s for arc "%s".', max_arc_delivery_time, bs.ForBeam.Name)
    except Exception as e:
        logger.exception(e)
        raise
Exemple #27
0
        score = yaml.load(resources['score'])
        if 'cleanup-scripts' in score and 'scripts' in resources:
            score['cleanup-scripts'] = normalize(score['cleanup-scripts'],
                                                 score)
            for script, args in score['cleanup-scripts'].iteritems():
                for id, data in resources['scripts'].iteritems():
                    if data['name'] == script:
                        print 'executing cleanup script {}'.format(script)
                        rc, out, err = run_script_text(data['text'], args)
                        if rc != 0:
                            print out
                            print err

        state_container_clean(sl_storage, containername)
    else:
        error('cluster does not exist')


def main():
    args = docopt(__doc__, version='kleiber cluster director  0.1')
    try:
        configuration = yaml.load(
                open(os.environ['HOME']+'/.kleiber', 'r').read())
    except IOError:
        error('kleiber configuration file {} not found'.format(
                    os.environ['HOME']+'/.kleiber'))

    client = SoftLayer.create_client_from_env(
                          username=configuration['username'],
                          api_key=configuration['api_key'])
Exemple #28
0
                                 '*').read().split("\n")
                files.pop()
                i = 0
                while i < len(files) - folder['limit']:
                    os.system('rm ' + files[i])
                    i = i + 1

        for exe in dump['exec']:
            os.system(exe.replace('$file', x['tmp'] + '/' + file))

    os.system('rm -rf ' + x['tmp'])
    print "Finish all routines!"

elif x['mode'] == "--extract":
    if not x['file']:
        lib.error("You must pass a file as argument!")
    if not os.path.isfile(x['file']):
        lib.error("File <" + x['file'] + "> not found!")

    dumps = lib.loadConfig(x['source'])['dump']

    os.system('rm -rf ' + x['tmp'])
    os.system('mkdir -p ' + x['tmp'])
    os.system('cp ' + x['file'] + ' ' + x['tmp'])
    os.chdir(x['tmp'])

    file = x['file'][x['file'].rfind("/") + 1:]
    ext = ".enc"
    if (file[len(file) - len(ext):] == ext):
        file = file[0:len(file) - len(ext)]
Exemple #29
0
        score = yaml.load(resources['score'])
        if 'cleanup-scripts' in score and 'scripts' in resources:
            score['cleanup-scripts'] = normalize(score['cleanup-scripts'],
                                                 score)
            for script, args in score['cleanup-scripts'].iteritems():
                for id, data in resources['scripts'].iteritems():
                    if data['name'] == script:
                        print 'executing cleanup script {}'.format(script)
                        rc, out, err = run_script_text(data['text'], args)
                        if rc != 0:
                            print out
                            print err

        state_container_clean(sl_storage, containername)
    else:
        error('cluster does not exist')


def main():
    args = docopt(__doc__, version='kleiber cluster director  0.1')
    try:
        configuration = yaml.load(
            open(os.environ['HOME'] + '/.kleiber', 'r').read())
    except IOError:
        error('kleiber configuration file {} not found'.format(
            os.environ['HOME'] + '/.kleiber'))

    client = SoftLayer.create_client_from_env(
        username=configuration['username'], api_key=configuration['api_key'])

    if 'obj_store' not in configuration:
Exemple #30
0
    def DNS_Query_Interface(self, domain):
        """
        DNS接口查询
        """
        # threadLock.acquire()
        #方法:add_cookie(cookie={'':'','':''})
        try:
            datas_d1 = []
            datas_d2 = []
            warning(('Query Domain -> ' + domain))
            selenium_.browser_.get(dns_query1.format(domain))
            time.sleep(7)
            htmldoc = selenium_.browser_.find_element_by_xpath(
                '/html/body/pre').text
            data = loads(htmldoc)
            # info(data['RDNS'])
            try:
                if 'FDNS_A' in data:
                    data1 = data['FDNS_A']
                    for data_1 in data1:
                        find1 = re.findall(regular(1), data_1)
                        find2 = re.findall(regular(2), data_1)
                        find3 = re.findall(regular(3), data_1)
                        d1 = data_1.split(',')

                        if find1:
                            ips = d1[0]
                        if find2 or find3:
                            domains = d1[1]
                        if ips or domains:
                            datas_d1.append([ips, domains])

            except:
                pass

            try:
                if 'RDNS' in data:
                    data2 = data['RDNS']
                    for data_2 in data2:
                        find1 = re.findall(regular(1), data_2)
                        find2 = re.findall(regular(2), data_2)
                        find3 = re.findall(regular(3), data_2)
                        d2 = data_2.split(',')
                        if find1:
                            ips = d2[0]
                        if find2 or find3:
                            domains = d2[1]
                        if ips or domains:
                            datas_d2.append([ips, domains])
            except:
                pass

            foo.Dns_Qery = [datas_d1, datas_d2]

            for d1 in foo.Dns_Qery[0]:
                ip = d1[0]
                if ip:
                    domain = d1[1]
                    thread1 = threading.Thread(target=self.port_scan,
                                               args=(ip, ip))
                    time.sleep(1)
                    thread1.start()
                    info('域名:{} -> 查询IP:{}'.format(domain, ip))

            for d1 in foo.Dns_Qery[1]:
                ip = d1[0]
                if ip:
                    domain = d1[1]
                    thread2 = threading.Thread(target=self.port_scan,
                                               args=(ip, ip))
                    time.sleep(1)
                    thread2.start()
                    info('域名:{} -> 查询IP:{}'.format(domain, ip))

            selenium_.browser_.quit()
            return True

        except Exception as e:
            selenium_.browser_.quit()
            error(traceback.format_exc())
            i = 0
            while True:
                if i == 3:
                    if self.DNS_Query_Interface(domain=domain):
                        break
                    i = 0
                i += 1
Exemple #31
0
        "ip":
        "string: ip address format xxx.xxx.xxx.xxx for dynamic ip use range like xxx.xxx.xxx.xxx-xxx"
    }]
    lib.storeConfig(x['source'], hosts)

elif x['host']:
    hosts = lib.loadConfig(x['source'])

    host = False
    for h in hosts:
        if h['label'] == x['host']:
            host = h
            break

    if not host:
        lib.error("Unknown host <" + x['host'] + ">")

    ipAddress = ip(host)
    if not ipAddress:
        lib.error("<" + x['host'] + "> is down")

    flags = ''
    if host['ip'].find("-") != -1:
        flags = ' -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'

    if x['action'] == 'put':
        if not x['dest']:
            x['dest'] = '.'
        os.system("scp -r -P " + host['port'] + ' ' + x['src'] + ' ' +
                  host['user'] + "@" + ipAddress + ':' + x['dest'])