예제 #1
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def run(self):
     while True:
         try:
             self.getUserOptions()
         except KeyboardInterrupt:
             Console.info('Quitting')
             break
예제 #2
0
    def __init__(self, *args, **kwargs):
        super(HxatLocust, self).__init__(*args, **kwargs)

        # log to stdout
        self.console = Console()

        # default is verbose=True
        self.verbose = os.environ.get("HXAT_LOCUST_VERBOSE", "true").lower() == "true"

        # settings for this hxat user instance
        random_user = os.environ.get("FORCE_SINGLE_USER", "false").lower() == "false"
        self.hxat_client = get_hxat_client(cat="from_env", random_user=random_user)

        # TODO: this dumps lots of message for each http request
        self.ssl_verify = (
            os.environ.get("HXAT_LOCUST_SSL_VERIFY", "false").lower() == "true"
        )

        # check if should use ssl (for ws)
        self.use_ssl = self.host.startswith("https")

        # do not create ws-client until a successful lti-launch
        self.ws_client = None

        for attr, value in vars(self.hxat_client).items():
            self.console.write("----- {} = {} ".format(attr, value))
        for attr, value in vars(self).items():
            self.console.write("***** {} = {}".format(attr, value))
예제 #3
0
파일: wsclient.py 프로젝트: nmaekawa/hxat
    def __init__(
        self,
        host,
        hxat_utm_source,
        hxat_resource_link_id,
        app_url_path="",
        timeout=2,
        verbose=False,
        use_ssl=True,
    ):
        self.console = Console()
        self.host = host
        self.hxat_utm_source = hxat_utm_source
        self.hxat_resource_link_id = hxat_resource_link_id
        self.ws_timeout = timeout
        self.verbose = verbose
        self.session_id = uuid4().hex
        self.protocol = "wss" if use_ssl else "ws"

        h = urlparse(self.host)
        self.hostname = h.netloc

        self.app_url_path = app_url_path

        self.ws = None
        self.thread = None

        events.quitting += self.on_close
예제 #4
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def get_pdf_file(self):
     try:
         print(f"[+] file being processed {self.file}")
         return PdfFileReader(self.file)
     except FileNotFoundError as e:
         Console.error(e)
         exit(1)
예제 #5
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def run(self):
     Console.log('Lets clone you some sites')
     time.sleep(.25)
     self.get_website_url()
     time.sleep(.25)
     self.get_path_to_store_cloned_site()
     self.clone_site()
예제 #6
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def compress_operation(self):
     time.sleep(.5)
     Console.log(
         'Compress files and folders, even encrypt them if option chosen')
     is_valid = False
     while is_valid is False:
         abs_path_turple, is_valid = self.get_user_input()
     self.process_compression(abs_path_turple)
예제 #7
0
파일: libs.py 프로젝트: addy360/my_py_Lib
def appFactory(choice, modules):
    try:
        Console.info(f"{modules[str(choice)]['desc']}")
        time.sleep(.5)
        return modules[str(choice)]['name']()
    except KeyError as e:
        Console.error('Wrong module')
        exit(1)
예제 #8
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def getUserOptions(self):
        self.instructions()
        self.get_user_choice()

        while self.is_choice_valid(self.user_choice) is False:
            Console.error('Please enter a valid option')
            self.get_user_choice()
        self.generate_password()
예제 #9
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def parse_next_page(self, next_page_url):
        Console.info('Going to next page')
        # TODO caching for easier backward navigation
        # self.cached_posts[self.URL] = self.posts
        self.posts = []
        self.URL = next_page_url

        self.parse_result()
예제 #10
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def write_encripted_data_to_file(self, file_data):
     file = f'encrypted_{self.file_name}'
     file = os.path.join(self.file_root_dir, file)
     Console.info('Writting encrypted data to file...')
     with open(file, 'wb') as f:
         time.sleep(1)
         file_data.write(f)
         Console.log(f'{file} written successfully')
예제 #11
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def print_posts(self, posts):
     for i, post in enumerate(posts):
         time.sleep(.2)
         Console.warn(f'{i+1} : {post.h2.a.text}')
         self.posts.append({
             'post_title': post.h2.a.text,
             'post_link': post.h2.a['href']
         })
예제 #12
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def get_place(self):
     place_name = input(
         f"\n{Console.green('Where to find the file (Valid path) > ')}")
     folder_path = get_file_or_folder_path(place_name)
     if folder_path:
         self.folder_path = folder_path
         return
     Console.error('Path should be valid...')
     self.get_place()
예제 #13
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def get_path_to_store_cloned_site(self):
     path_to_store = input(
         f"\n{Console.green('Enter path to store cloned site ( Leave empty to store in current directory ) > ')}"
     )
     path_to_store = get_file_or_folder_path(path_to_store)
     if path_to_store == None:
         Console.error('Invalid path. Please try again!')
         return self.get_path_to_store_cloned_site()
     self.path_to_store = path_to_store[0]
예제 #14
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def get_file(self):
     file_name = input(
         f"\n{Console.green('Enter name of a file you would like to find > ')}"
     )
     valid = len(file_name.strip()) > 1
     if valid:
         self.file_name = file_name
         return
     Console.error('Can not be empty, please try again...')
     self.get_file()
예제 #15
0
 def next(self):
     self.current_state, _ = self.act(self.current_state)
     if self.is_winning_state(self.current_state):
         Console.print("-1 -1")
         Debug.print("Player won.")
         return False
     elif self.is_losing_state(self.current_state):
         Console.print("-1 -1")
         Debug.print("Player lost.")
         return False
     return True
예제 #16
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def parse_post_details(self, post_detail_html):
     soup = self.get_soup(post_detail_html)
     post_header = soup.select_one('div#post-header>h1').text
     post_content = soup.select_one('div.post-section')
     print('\n')
     print(Console.yellow(line(post_header)))
     print(post_header)
     print(Console.yellow(line(post_header)))
     print('\n')
     post_detail = post_content.text.strip()
     print(post_detail)
예제 #17
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def run(self):
     self.get_file()
     passwd = input(
         f'Please enter a secure password Default ({self.passwd})> ')
     if passwd.strip():
         self.passwd = passwd
     try:
         self.enc_pdf()
     except Exception as e:
         Console.error(str(e))
         self.run()
예제 #18
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def process_compression(self, path_to_file):
        root_dir = path_to_file[2]
        f_name = path_to_file[1]
        compressed_file, was_success = self.compress(root_dir, path_to_file)

        choice = input(
            f"\n{Console.green(f'Encrypt { compressed_file[0] } ? (Y/n)')}")
        if choice.lower() not in ['n', 'y'] or choice.lower() == 'n':
            Console.info('Bye!!')
            return
        self.encrypt_file(compressed_file)
예제 #19
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def get_file(self):
     file = input('Please enter a valid pdf file name > ')
     file_path, file_name, file_root_dir = get_file_or_folder_path(file)
     if not file_path or file_name.split('.')[-1].lower() != 'pdf':
         Console.error(
             f'{file} does not exist or not pdf. Try again or (Ctrl + C) to quit'
         )
         self.get_file()
     self.file = file_path
     self.file_name = file_name
     self.file_root_dir = file_root_dir
예제 #20
0
파일: libs.py 프로젝트: addy360/my_py_Lib
def main(modules):
    time.sleep(.3)
    Console.info('Welcome to libs helper\n')
    time.sleep(.5)
    instructions(modules)
    try:
        choice = int(input('\nPick your poison > '))
        app = appFactory(choice, modules)
        app.run()
    except ValueError as e:
        Console.error('Invalid input')
        exit(1)
예제 #21
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def validate_path(self, path):
        if len(path) == 0:
            Console.error('Path can not be empty')
            return None, False
        abs_path_turple = get_file_or_folder_path(path)

        if not abs_path_turple:
            Console.error(
                'Path to file or folder does not exist. Try again...')
            return None, False

        return abs_path_turple, True
예제 #22
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def compress(self, root_dir, path_to_file):
        if os.path.isdir(path_to_file[0]):
            compress_name = f'{path_to_file[0]}.tar.gz'
        elif os.path.isfile(path_to_file[0]):
            file_name = path_to_file[0]
            file_name = file_name.split('.')[-2]
            compress_name = f'{file_name}.tar.gz'
        time.sleep(.3)
        Console.info(f'Compressing to {compress_name}, please wait...')
        self.actual_compression(path_to_file[0])

        return path_to_file, True
예제 #23
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def user_choice(self, next_page_url=None):
     choice = input(
         f"\n{Console.green('Enter (n) for next page or post number for post details > ')}"
     )
     try:
         post_url = self.posts[int(choice) - 1]['post_link']
         self.get_post_details(post_url)
     except Exception:
         if choice.strip().lower() == 'n':
             self.parse_next_page(next_page_url)
         else:
             Console.error("Wrong choice")
             self.user_choice()
예제 #24
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def decompress_operation(self):
     time.sleep(.3)
     path = input(
         f"\n{Console.green('Enter path to file or folder you want to decompress > ')}"
     )
     file_path_turple, is_path_valid = self.validate_path(path)
     if is_path_valid is not True:
         self.decompress_operation()
     if self.process_de_compression(file_path_turple) is not True:
         self.decompress_operation()
     Console.log('Done decompressing...')
     time.sleep(.3)
     self.remove_file(file_path_turple[0])
예제 #25
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def get_copy_destination(self):
        dest = input(
            f"\n{Console.green('Do you wish to copy these files to?  > ')}")

        folder_name = input(
            f"\n{Console.yellow('Folder name to store files ? > ')}")

        destination_turple = get_file_or_folder_path(dest)
        if destination_turple is not None and folder_name.strip():
            return destination_turple[0], folder_name
        else:
            Console.error(
                'Invalid path or missing folder name. Please try again!')
            return self.get_copy_destination()
예제 #26
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def enc_pdf(self):
        parser = PdfFileWriter()
        Console.info(f'Loading {self.file}...')
        time.sleep(.5)
        pdf = self.get_pdf_file()
        for page in range(pdf.numPages):
            parser.addPage(pdf.getPage(page))
        Console.info('Encrypting data...')
        time.sleep(.4)
        parser.encrypt(self.passwd)

        self.write_encripted_data_to_file(parser)
        time.sleep(.2)
        self.choose_to_delete(self.file)
예제 #27
0
 def __init__(self, cfg, curr, targ):
     self.cfg = cfg
     self.LOG = Console()
     
     # 상태 : active, standby
     # curr : 현재상태
     # targ : 다음상태
     self.curr = curr
     self.targ = targ
예제 #28
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def process_de_compression(self, filename):
        if not filename:
            return
        file_path, file_name, parent_dir = filename
        # print(shutil.get_unpack_formats())

        extraction_file_name = ''.join(file_name.split('.')[:-2])
        extraction_folder_name = os.path.join(parent_dir, extraction_file_name)

        Console.log(
            f'Decompressing to { extraction_folder_name } , Please wait...')
        time.sleep(.3)
        try:
            shutil.unpack_archive(filename=file_path,
                                  extract_dir=extraction_folder_name)
            return True
        except shutil.ReadError as e:
            Console.error('Folder not of valid type')
            return False
예제 #29
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def get_user_input(self):
        choice = None
        try:
            choice = int(
                input(
                    f"\n{Console.green('Choose (1) for media files, (2) for other queries > ')}"
                ))
        except Exception:
            pass

        if choice not in [1, 2]:
            Console.error('Wrong input. Please try again!')
            return self.get_user_input()

        if choice == 2:
            self.get_file()
        else:
            self.file_name = self.supported_media_files
        self.get_place()
        return self.file_name, self.folder_path
예제 #30
0
파일: libs.py 프로젝트: addy360/my_py_Lib
 def generate_password(self):
     passwd_chars = self.get_chosen_chars()
     Console.info(f'Your choice {passwd_chars}')
     time.sleep(.2)
     Console.info('Generating password, Please wait...')
     time.sleep(1)
     pass_list = random.sample(passwd_chars, int(self.password_length))
     generated_passwd = "".join(pass_list)
     Console.info(
         f'Your newly generated password is {Console.green(generated_passwd)}'
     )
     time.sleep(.4)
     Console.log('[+] Done')
     raise KeyboardInterrupt
예제 #31
0
파일: libs.py 프로젝트: addy360/my_py_Lib
    def choose_to_delete(self, file_name):
        choice = input(
            Console.yellow(f'Do you wish to delete {file_name}? (N/y) > '))
        choice = choice.strip().lower()
        not_valid = choice not in ['n', 'y']
        if not_valid:
            Console.error('Please choose a valid input!')
            time.sleep(.2)
            self.choose_to_delete(file_name)

        if choice == 'n':
            Console.log('Bye!')
            return
        Console.info(f'Deleting {file_name}...')
        delete_file(file_name)
예제 #32
0
class UTMFailOver:
    
    def __init__(self, cfg, curr, targ):
        self.cfg = cfg
        self.LOG = Console()
        
        # 상태 : active, standby
        # curr : 현재상태
        # targ : 다음상태
        self.curr = curr
        self.targ = targ
        
    def loop_l3_connectivity(self, run_l3_check=False, max_count = 10, time_sleep=3):
        # L3 연결성 체크    
        count = 0
        if run_l3_check:
            while (count < max_count):
                if self.check_l3():
                    break
                self.LOG.log(" ====================================================")
                if count != max_count-1: time.sleep(time_sleep)
                count = count + 1
                    
    # utm의 interface가 올라왔는지 ping과 arp로 확인한다.
    # target의 ip 주소로 ping을 하고,
    # 그 결과 arp를 확인하여 mac주소가 설정값과 동일한지 확인  
    def is_l3_connected(self, ip_addr, mac_in_cfg):
        mac_in_real = NetUtil().get_mac_from_arp(ip_addr)
        
        self.LOG.log("     - CONF ip= %-15s mac= %s" % (ip_addr, mac_in_cfg))
        self.LOG.log("     - REAL ip= %-15s mac= %s" % (ip_addr, mac_in_real))
        
        if mac_in_cfg.upper() == mac_in_real.upper():
            return True
        else:
            return False

    def check_l3(self):
        customer = self.cfg.get("failover", "customer")
        ip_red = self.cfg.get(customer, "ip_red")
        ip_green = self.cfg.get(customer, "ip_green")
        
        mac_red_in_cfg = self.cfg.get(self.target, "port_red_mac")
        mac_green_in_cfg = self.cfg.get(self.target, "port_green_mac")
        
        self.LOG.info(" *** [INFO] Checking L3 connectivity...")
        
        red_l3_failover = is_l3_connected(ip_red, mac_red_in_cfg)
        green_l3_failover = is_l3_connected(ip_green, mac_green_in_cfg)
        
        if red_l3_failover and green_l3_failover:
            self.LOG.info(" ***                             성공!!!")
            return True
        else:
            self.LOG.error(" ***                             진행중!!!")
            return False

    #  L2 연결성 체크, 성공시 L3 연결 체크 문의
    def loop_l2_connectivity(self, ask_l3_check=False, max_count = 10, time_sleep=3 ):
        run_l3_check=False
            
        count = 0
        while (count < max_count):
            if self.check_l2():
                if ask_l3_check: 
                    run_l3_check=InteractionUtil().ask_user("L3 연결을 체크하시겠습니까?")                
                break
            self.LOG.log(" ====================================================")
            if count != max_count-1: time.sleep(time_sleep)
            count = count + 1
        return run_l3_check  
    
    # 스위치 인터페이스 중 active가 disable되고
    # standby가 active되었는지를 확인
    def is_l2_connected(self, intf_curr, intf_targ):
        l2_connected = False
        if intf_curr.is_disabled() and intf_targ.is_enabled():
            l2_connected = True
        else:
            l2_connected = False
        
        return l2_connected
    
    # switch의 interface가 올라왔는지 확인한다.
    # current interface는 down되고, target interface는 up 
    def check_l2(self):
        port_red_curr = self.cfg.get(self.curr, "port_red")
        port_red_targ = self.cfg.get(self.targ, "port_red")
        
        port_green_curr = self.cfg.get(self.curr, "port_green")
        port_green_targ = self.cfg.get(self.targ, "port_green")
        
        intf_red_curr = Interface(port_red_curr)
        intf_red_targ = Interface(port_red_targ)
        intf_green_curr = Interface(port_green_curr)
        intf_green_targ = Interface(port_green_targ)
        
        red_failover = self.is_l2_connected(intf_red_curr, intf_red_targ)
        green_failover = self.is_l2_connected(intf_green_curr, intf_green_targ)
        
        self.LOG.info(" *** [INFO] Checking L2 connectivity...")
    
        self.LOG.log("     - %-5s interface failover result= %s" % ("RED", red_failover))
        self.LOG.log("     - %-5s interface failover result= %s" % ("GREEN", green_failover))
        
        if red_failover and green_failover:
            self.LOG.log(" ----------------------------------------------------")
            self.LOG.info(" ***                                          성공!!!")
            self.LOG.log(" ----------------------------------------------------")
            return True
        else:
            self.LOG.log(" ----------------------------------------------------")
            self.LOG.error(" ***                                        진행중!!!")
            self.LOG.log(" ----------------------------------------------------")        
            return False

    def failover(self, curr, targ):
        curr_port_green = self.cfg.get(curr, "port_green")
        curr_port_red = self.cfg.get(curr, "port_red")
        targ_port_green = self.cfg.get(targ, "port_green")
        targ_port_red = self.cfg.get(targ, "port_red")
        
        intf_curr_green = Interface(curr_port_green)
        intf_curr_red = Interface(curr_port_red)
        
        intf_targ_green = Interface(targ_port_green)
        intf_targ_red = Interface(targ_port_red)
        
        self.LOG.info(" *** [INFO] Running failover for GREEN interface")
        self.LOG.log("     - Shutdown interface= %s" % intf_curr_green.interface_id)
        intf_curr_green.shutdown(True)
        
        self.LOG.log("     - Enable interface= %s" % intf_targ_green.interface_id)
        intf_targ_green.shutdown(False)
        
        self.LOG.info(" *** [INFO] Running failover for RED interface")
        self.LOG.log("     - Shutdown interface= %s" % intf_curr_red.interface_id)
        intf_curr_red.shutdown(True)
        
        self.LOG.log("     - Enable interface= %s" % intf_targ_red.interface_id)
        intf_targ_red.shutdown(False)  
        
        self.LOG.log(" ----------------------------------------------------")


    def is_applied(self, cfg_name):
        customer = self.cfg.get("failover", "customer")
        
        cfg_red_ip = self.cfg.get(customer, "red_ip")
        cfg_green_ip = self.cfg.get(customer, "green_ip")
        
        cfg_red_port = self.cfg.get(cfg_name, "port_red")
        cfg_green_port = self.cfg.get(cfg_name, "port_green")
        cfg_orange_port = self.cfg.get(cfg_name, "port_orange")
        
        intf_red = Interface(cfg_red_port)
        intf_green = Interface(cfg_green_port)
        intf_orange = Interface(cfg_orange_port)
        
        if intf_red.is_enabled() and intf_green.is_enabled() and intf_orange.is_enabled():
            return True
        else:
            return False
                
    def show_config(self, cfg_name, title):
        self.LOG.log(" ----------------------------------------------------")
        self.LOG.info(" *** %s (%s)" % ( title, cfg_name) )
        self.LOG.log(" ----------------------------------------------------")
    
        customer = self.cfg.get("failover", "customer")
        
        cfg_red_ip = self.cfg.get(customer, "red_ip")
        cfg_green_ip = self.cfg.get(customer, "green_ip")
        
        cfg_red_port = self.cfg.get(cfg_name, "port_red")
        cfg_green_port = self.cfg.get(cfg_name, "port_green")
        cfg_orange_port = self.cfg.get(cfg_name, "port_orange")
        
        intf_red = Interface(cfg_red_port)
        intf_green = Interface(cfg_green_port)
        intf_orange = Interface(cfg_orange_port)
        
        self.LOG.info(" - %s" % "RED")
        self.LOG.log("     . switch port= %s (%s)" % (cfg_red_port, intf_red.get_status()))
        self.LOG.log("     . ip address = %s" % cfg_red_ip)
        
        self.LOG.info(" - %s" % "GREEN")
        self.LOG.log("     . switch port= %s (%s)" % (cfg_green_port, intf_red.get_status()))
        self.LOG.log("     . ip address = %s" % cfg_green_ip)
        
        self.LOG.info(" - %s" % "ORANGE")
        self.LOG.log("     . switch port= %s (%s)" % (cfg_orange_port, intf_red.get_status()))
        
        self.LOG.log(" ----------------------------------------------------")
예제 #33
0
파일: cli.py 프로젝트: szaffarano/demeter
    'write_event': [],
    'disable_event': [],
    'enable_event': [],
    'read_events': [],
    'disable_event': [],
    'enable_event': [],
    'disable_relay': [],
    'enable_relay': [],
    'temperatura': [],
    'humedad': [],
    'luz': [],
}

if __name__ == '__main__':
    demeter = DemeterClient(MODBUS_CLIENT_ID, modbus_config)
    console = Console(autocompletions, HISTORY_FILENAME)

    while True:
        cli = console.input('modbus> ')

        command = cli[0]
        arguments = cli[1:] if len(cli) > 1 else []

        if not demeter.is_valid(command):
            print "%s: comando desconocido." % command
            continue

        response = demeter.execute(command, arguments)
        if response is None:
            print "respuesta nula"
        elif isinstance(response, ExceptionResponse):