How to use get_num_hosts method in autotest

Best Python code snippet using autotest_python

IPscanner.py

Source:IPscanner.py Github

copy

Full Screen

...145 else:146 return ipaddress.ip_address(start_ipaddr)147148149def get_num_hosts() -> Union[int, None]:150 """151 Функция возвращает число хостов для проверки или None152 """153 num_hosts: str = input("Введите количество хостов для проверки: ")154155 while num_hosts != "q":156 if not num_hosts.isdigit():157 print()158 print("Вы ввели не число")159 num_hosts = input("Введите количество хостов или q для выхода: ")160 else:161 break162163 if num_hosts == "q":164 return None165 else:166 return int(num_hosts)167168169###############################################################################170# Main function #171###############################################################################172def host_range_ping() -> Union[Dict[str, List[str]], None]:173 """174 Функция пингует диапазон IP-адресов175 и возвращает словарь со списком доступных176 и недоступных IP-адресов или None177 """178 start_addr: Union[179 ipaddress.IPv4Address, ipaddress.IPv6Address, None180 ] = get_start_addr()181 if start_addr is None:182 print("IP-адрес не был получен")183 print("Выход")184 return None185186 num_hosts: Union[int, None] = get_num_hosts()187 if num_hosts is None:188 print("Количество хостов не было получено")189 print("Выход")190 return None191192 # Создаём генератор объектов IP-адресов для проверки193 hosts_gen: Iterator[str] = (str(start_addr + i) for i in range(num_hosts))194195 # Вызываем функцию проверки доступности196 all_ipaddrs_dict: Union[Dict[str, List[str]], None] = host_ping(hosts_gen)197 return all_ipaddrs_dict198199200############################################################################### ...

Full Screen

Full Screen

forms.py

Source:forms.py Github

copy

Full Screen

...61 as_binary = as_binary.rjust(32, "0")62 parts = [as_binary[start:start + 8] for start in range(0, 32, 8)]63 return ".".join(str(int(part.ljust(8, "0"), 2)) for part in parts)64 @staticmethod65 def get_num_hosts(cidr):66 """67 Return the number of hosts available to a subnet described in the CIDR68 notation (number of contiguous leading bits).69 Note: although this isn't necesarily to be used as a filter, it follows70 the Django convention of returning an empty string on malformed input.71 """72 if not isinstance(cidr, int):73 return ""74 return 2 ** (32 - cidr) - 275 def get_6to4_prefix(self, address):76 if not address:77 return ""78 parts = (int(part) for part in self.int_to_human(address).split("."))79 return "2002:%x%x:%x%x::/48" % tuple(parts)80 def get_network_information(self):81 """82 Return a dict containing the most comprehensive possible set of83 information about a particular network, given the current state of84 self.cleaned_data.85 """86 address = self.cleaned_data.get("address")87 network = self.cleaned_data.get("network")88 mask = self.cleaned_data.get("mask")89 cidr = self.cleaned_data.get("cidr")90 hostname = self.cleaned_data.get("hostname")91 if hostname:92 try:93 address = self.human_to_int(socket.gethostbyname(hostname))94 except socket.gaierror:95 address = ""96 hostname = ""97 elif address:98 try:99 hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(address)100 except socket.herror:101 hostname = ""102 address = self.human_to_int(address)103 else:104 hostname = ""105 prefix_6to4 = self.get_6to4_prefix(address)106 if isinstance(cidr, int):107 # Force CIDR number to be between 0 and 30, inclusive.108 cidr = max(0, cidr)109 cidr = min(30, cidr)110 mask = int(("1" * cidr).ljust(32, "0"), 2)111 elif mask:112 mask = self.human_to_int(mask)113 cidr = bin(mask).count("1")114 num_hosts = self.get_num_hosts(cidr)115 if address and isinstance(mask, int):116 network = address & mask117 elif network:118 network = self.human_to_int(network)119 if isinstance(network, int):120 first_host = network + 1121 last_host = network + num_hosts122 broadcast = network + num_hosts + 1123 else:124 network = None125 first_host = None126 last_host = None127 broadcast = None128 return ({...

Full Screen

Full Screen

passive_dns_lookup.py

Source:passive_dns_lookup.py Github

copy

Full Screen

1import argparse2import dnsdb23from dotenv import load_dotenv4import logging 5import os6import sys7from time import sleep8load_dotenv() 9logging.basicConfig(level=logging.DEBUG,10 format='%(asctime)s %(levelname)-8s %(message)s',11 datefmt='%Y-%m-%dT%H:%M:%S',12 filename='passive_dns_lookup.log',13 filemode='w')14def dnsdb_request_setup(ip):15 """Setup and name variables for DNSDB API Client.16client = dnsdb2.Client()17results = client.summarize_rdata_ip()18"""19 dnsdb_key = os.getenv("DNSDB_KEY")20 client = dnsdb2.Client(dnsdb_key)21 results = next(client.summarize_rdata_ip(ip))22 return results23def single_fetch_dnsdb_results(target):24 """Get results for a single IP address, used with the '--ip' arg.25get_num_hosts = result of dnsdb_request_setup()26The 'num_results' key holds the number of hosts associated with an IP address.27"""28 29 get_num_hosts = dnsdb_request_setup(ip=target)30 if get_num_hosts['num_results'] < 100:31 return f'IP: {target} has a low number of hosts, you may want to block'32 else:33 return f'IP: {target} has a large number of hosts, block with caution'34def multiple_fetch_dnsdb_results(target):35 """Get results for a file of IP addresses, used with the '--file' arg.36Still a work in progress.37"""38 with open(target, 'r') as f:39 for line in f:40 search_term = line.strip(' \n')41 42 get_multi_hosts = dnsdb_request_setup(ip=search_term)43 if get_multi_hosts['num_results'] < 100:44 print(f'[*] IP: {search_term} has a low number of hosts, you may want to block \n')45 if len(search_term) >= 5:46 sleep(20)47 48 print(f'[!] IP: {search_term} has a large number of hosts, block with caution')49def parse_args():50 parser = argparse.ArgumentParser(description='Args')51 parser.add_argument('-f', '--file', help='path to file of IP addresses')52 parser.add_argument('-i', '--ip', help='Specifiy single IP address to lookup')53 args = parser.parse_args()54 return args 55def main():56 args = parse_args()57 if args.ip:58 print(single_fetch_dnsdb_results(args.ip))59 if args.file:60 print(multiple_fetch_dnsdb_results(args.file))61 else:62 print("Couldn't understand your request, try again")63 sys.exit(1)64 65if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful