Misc Helpers
These are miscellaneous helpers, used throughout BBOT and its modules for simple tasks such as parsing domains, ports, urls, etc.
as_completed
async
as_completed(coros)
Async generator that yields completed Tasks as they are completed.
Parameters:
-
coros
(iterable
) –An iterable of coroutine objects or asyncio Tasks.
Yields:
-
–
asyncio.Task: A Task object that has completed its execution.
Examples:
>>> async def main():
... async for task in as_completed([coro1(), coro2(), coro3()]):
... result = task.result()
... print(f'Task completed with result: {result}')
>>> asyncio.run(main())
Source code in bbot/core/helpers/misc.py
2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 |
|
backup_file
backup_file(filename, max_backups=10)
Renames a file by appending an iteration number as a backup. Recursively renames files up to a specified maximum number of backups.
Parameters:
-
filename
(str or Path
) –The file to backup.
-
max_backups
(int
, default:10
) –The maximum number of backups to keep. Defaults to 10.
Returns:
-
–
pathlib.Path: The new backup filepath.
Examples:
>>> backup_file("/tmp/test.txt")
PosixPath("/tmp/test.0.txt")
>>> backup_file("/tmp/test.0.txt")
PosixPath("/tmp/test.1.txt")
>>> backup_file("/tmp/test.1.txt")
PosixPath("/tmp/test.2.txt")
Source code in bbot/core/helpers/misc.py
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 |
|
best_http_status
best_http_status(code1, code2)
Determine the better HTTP status code between two given codes.
The 'better' status code is considered based on typical usage and priority in HTTP communication. Lower codes are generally better than higher codes. Within the same class (e.g., 2xx), a lower code is better. Between different classes, the order of preference is 2xx > 3xx > 1xx > 4xx > 5xx.
Parameters:
Returns:
-
int
–The better HTTP status code between the two provided codes.
Examples:
>>> better_http_status(200, 404)
200
>>> better_http_status(500, 400)
400
>>> better_http_status(301, 302)
301
Source code in bbot/core/helpers/misc.py
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 |
|
bytes_to_human
bytes_to_human(_bytes)
Convert a bytes size to a human-readable string.
This function converts a numeric bytes value into a human-readable string format, complete with the appropriate unit symbol (B, KB, MB, GB, etc.).
Parameters:
-
_bytes
(int
) –The number of bytes to convert.
Returns:
-
str
–A string representing the number of bytes in a more readable format, rounded to two decimal places.
Examples:
>>> bytes_to_human(1234129384)
'1.15GB'
Source code in bbot/core/helpers/misc.py
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 |
|
calculate_entropy
calculate_entropy(data)
Calculate the Shannon entropy of a byte sequence
Source code in bbot/core/helpers/misc.py
2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 |
|
can_sudo_without_password
can_sudo_without_password()
Check if the current user has passwordless sudo access.
This function checks whether the current user can use sudo without entering a password. It runs a command with sudo and checks the return code to determine this.
Returns:
-
bool
–True if the current user can use sudo without a password, False otherwise.
Examples:
>>> can_sudo_without_password()
True
Source code in bbot/core/helpers/misc.py
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 |
|
cancel_tasks
async
cancel_tasks(tasks, ignore_errors=True)
Asynchronously cancels a list of asyncio tasks.
Parameters:
-
tasks
(list[Task]
) –A list of asyncio Task objects to cancel.
-
ignore_errors
(bool
, default:True
) –Whether to ignore errors other than asyncio.CancelledError. Defaults to True.
Examples:
>>> async def main():
... task1 = asyncio.create_task(async_function1())
... task2 = asyncio.create_task(async_function2())
... await cancel_tasks([task1, task2])
...
>>> asyncio.run(main())
Note
This function will not cancel the current task that it is called from.
Source code in bbot/core/helpers/misc.py
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 |
|
cancel_tasks_sync
cancel_tasks_sync(tasks)
Synchronously cancels a list of asyncio tasks.
Parameters:
-
tasks
(list[Task]
) –A list of asyncio Task objects to cancel.
Examples:
>>> loop = asyncio.get_event_loop()
>>> task1 = loop.create_task(some_async_function1())
>>> task2 = loop.create_task(some_async_function2())
>>> cancel_tasks_sync([task1, task2])
Note
This function will not cancel the current task from which it is called.
Source code in bbot/core/helpers/misc.py
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 |
|
chain_lists
chain_lists(l, try_files=False, msg=None, remove_blank=True, validate=False, validate_chars='<>:"/\\|?*)')
Chains together list elements, allowing for entries separated by commas.
This function takes a list l
and flattens it by splitting its entries on commas.
It also allows you to optionally open entries as files and add their contents to the list.
The order of entries is preserved, and deduplication is performed automatically.
Parameters:
-
l
(list
) –The list of strings to chain together.
-
try_files
(bool
, default:False
) –Whether to try to open entries as files. Defaults to False.
-
msg
(str
, default:None
) –An optional message to log when reading from a file. Defaults to None.
-
remove_blank
(bool
, default:True
) –Whether to remove blank entries from the list. Defaults to True.
-
validate
(bool
, default:False
) –Whether to perform validation for undesirable characters. Defaults to False.
-
validate_chars
(str
, default:'<>:"/\\|?*)'
) –When performing validation, what additional set of characters to block (blocks non-printable ascii automatically). Defaults to '<>:"/|?*)'
Returns:
-
list
–The list of chained elements.
Raises:
-
ValueError
–If the input string contains invalid characters, when enabled (off by default).
Examples:
>>> chain_lists(["a", "b,c,d"])
['a', 'b', 'c', 'd']
>>> chain_lists(["a,file.txt", "c,d"], try_files=True)
['a', 'f_line1', 'f_line2', 'f_line3', 'c', 'd']
Source code in bbot/core/helpers/misc.py
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 |
|
charset
charset(p)
Determine the character set of the given string based on the types of characters it contains.
Parameters:
-
p
(str
) –The string whose character set is to be determined.
Returns:
-
int
–A bitmask representing the types of characters present in the string. - CHAR_LOWER = 1: Lowercase alphabets - CHAR_UPPER = 2: Uppercase alphabets - CHAR_DIGIT = 4: Digits - CHAR_SYMBOL = 8: Symbols/Special characters
Examples:
>>> charset('abc')
1
>>> charset('abcABC')
3
>>> charset('abc123')
5
>>> charset('!abc123')
13
Source code in bbot/core/helpers/url.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
|
clean_dict
clean_dict(d, *key_names, fuzzy=False, exclude_keys=None, _prev_key=None)
Recursively clean unwanted keys from a dictionary. Useful for removing secrets from a config.
Parameters:
-
d
(dict
) –The input dictionary.
-
*key_names
–Names of keys to remove.
-
fuzzy
(bool
, default:False
) –Whether to perform fuzzy matching on keys.
-
exclude_keys
((list, None)
, default:None
) –List of keys to be excluded from removal.
-
_prev_key
((str, None)
, default:None
) –For internal recursive use; the previous key in the hierarchy.
Returns:
-
dict
–A dictionary cleaned of the keys specified in key_names.
Source code in bbot/core/helpers/misc.py
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 |
|
clean_dns_record
clean_dns_record(record)
Cleans and formats a given DNS record for further processing.
This static method converts the DNS record to text format if it's not already a string. It also removes any trailing dots and converts the record to lowercase.
Parameters:
-
record
(str or Rdata
) –The DNS record to clean.
Returns:
-
str
–The cleaned and formatted DNS record.
Examples:
>>> clean_dns_record('www.evilcorp.com.')
'www.evilcorp.com'
>>> from dns.rrset import from_text
>>> record = from_text('www.evilcorp.com', 3600, 'IN', 'A', '1.2.3.4')[0]
>>> clean_dns_record(record)
'1.2.3.4'
Source code in bbot/core/helpers/misc.py
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 |
|
clean_old
clean_old(d, keep=10, filter=lambda x: True, key=latest_mtime, reverse=True, raise_error=False)
Clean up old files and directories within a given directory based on various filtering and sorting options.
This function removes the oldest files and directories in the provided directory 'd' that exceed a specified threshold ('keep'). The items to be deleted can be filtered using a lambda function 'filter', and they are sorted by a key function, defaulting to latest modification time.
Parameters:
-
d
(str or Path
) –The directory path to clean up.
-
keep
(int
, default:10
) –The number of items to keep. Ones beyond this count will be removed.
-
filter
(Callable
, default:lambda x: True
) –A lambda function for filtering which files or directories to consider. Defaults to a lambda function that returns True for all.
-
key
(Callable
, default:latest_mtime
) –A function to sort the files and directories. Defaults to latest modification time.
-
reverse
(bool
, default:True
) –Whether to reverse the order of sorted items before removing. Defaults to True.
-
raise_error
(bool
, default:False
) –Whether to raise an error if directory deletion fails. Defaults to False.
Examples:
>>> clean_old("~/.bbot/scans", filter=lambda x: x.is_dir() and scan_name_regex.match(x.name))
Source code in bbot/core/helpers/misc.py
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 |
|
closest_match
closest_match(s, choices, n=1, cutoff=0.0)
Finds the closest matching strings from a list of choices based on a given string.
This function uses the difflib library to find the closest matches to a given string s
from a list of choices
.
It can return either the single best match or a list of the top n
best matches.
Parameters:
-
s
(str
) –The string for which to find the closest match.
-
choices
(list
) –A list of strings to compare against.
-
n
(int
, default:1
) –The number of best matches to return. Defaults to 1.
-
cutoff
(float
, default:0.0
) –A float value that defines the similarity threshold. Strings with similarity below this value are not considered. Defaults to 0.0.
Returns:
-
–
str or list: Either the closest matching string or a list of the
n
closest matching strings.
Examples:
>>> closest_match("asdf", ["asd", "fds"])
'asd'
>>> closest_match("asdf", ["asd", "fds", "asdff"], n=3)
['asdff', 'asd', 'fds']
Source code in bbot/core/helpers/misc.py
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 |
|
cloudcheck
cloudcheck(ip)
Check whether an IP address belongs to a cloud provider and returns the provider name, type, and subnet.
Parameters:
-
ip
(str
) –The IP address to check.
Returns:
-
tuple
–A tuple containing provider name (str), provider type (str), and subnet (IPv4Network).
Examples:
>>> cloudcheck("168.62.20.37")
('Azure', 'cloud', IPv4Network('168.62.0.0/19'))
Source code in bbot/core/helpers/misc.py
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 |
|
cpu_architecture
cpu_architecture()
Return the CPU architecture of the current system.
This function fetches and returns the architecture type of the CPU where the code is being executed. It maps common identifiers like "x86_64" to more general types like "amd64".
Returns:
-
str
–A string representing the CPU architecture, such as "amd64", "armv7", or "arm64".
Examples:
>>> cpu_architecture()
'amd64'
Source code in bbot/core/helpers/misc.py
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 |
|
delete_file
delete_file(path)
Deletes a file at the given path.
Parameters:
Note
This function suppresses all exceptions to ensure that the program continues running even if the file could not be deleted.
Examples:
>>> delete_file("/tmp/test/file1.txt")
Source code in bbot/core/helpers/misc.py
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 |
|
domain_parents
domain_parents(d, include_self=False)
Generate a list of parent domains for a given domain string.
This function takes an input string d
and generates a list of parent domains in decreasing order of specificity.
If include_self
is set to True, the list will also include the input domain if it is not a top-level domain.
Parameters:
-
d
(str
) –The input string representing a domain or subdomain.
-
include_self
(bool
, default:False
) –Whether to include the input domain itself. Defaults to False.
Yields:
-
str
–Parent domains of the input string in decreasing order of specificity.
Examples:
>>> list(domain_parents("test.www.evilcorp.co.uk"))
["www.evilcorp.co.uk", "evilcorp.co.uk"]
Notes
- Port, if present in input, is preserved in the output.
Source code in bbot/core/helpers/misc.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
|
domain_stem
domain_stem(domain)
Returns an abbreviated representation of the hostname by removing the TLD (Top-Level Domain).
Parameters:
-
domain
(str
) –The full domain name to be abbreviated.
Returns:
-
str
–An abbreviated domain string without the TLD.
Examples:
>>> domain_stem("www.evilcorp.com")
"www.evilcorp"
Notes
- Utilizes the
tldextract
function for domain parsing.
Source code in bbot/core/helpers/misc.py
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 |
|
execute_sync_or_async
async
execute_sync_or_async(callback, *args, **kwargs)
Execute a function or coroutine, handling either synchronous or asynchronous invocation.
Parameters:
-
callback
(Union[Callable, Coroutine]
) –The function or coroutine to execute.
-
*args
–Variable-length argument list to pass to the callback.
-
**kwargs
–Arbitrary keyword arguments to pass to the callback.
Returns:
-
Any
–The return value from the executed function or coroutine.
Examples:
>>> async def foo_async(x):
... return x + 1
>>> def foo_sync(x):
... return x + 1
>>> asyncio.run(execute_sync_or_async(foo_async, 1))
2
>>> asyncio.run(execute_sync_or_async(foo_sync, 1))
2
Source code in bbot/core/helpers/misc.py
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 |
|
extract_emails
extract_emails(s)
Extract email addresses from a body of text
This function takes in a string and yields all email addresses found in it. The emails are converted to lower case before yielding. It utilizes regular expressions for email pattern matching.
Parameters:
-
s
(str
) –The input string from which to extract email addresses.
Yields:
-
str
–Yields email addresses found in the input string, in lower case.
Examples:
>>> list(extract_emails("Contact us at info@evilcorp.com and support@evilcorp.com"))
['info@evilcorp.com', 'support@evilcorp.com']
Source code in bbot/core/helpers/misc.py
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 |
|
extract_host
extract_host(s)
Attempts to find and extract the host portion of a string.
Parameters:
-
s
(str
) –The string from which to extract the host.
Returns:
-
tuple
–A tuple containing three strings: (hostname (None if not found), string_before_hostname, string_after_hostname).
Examples:
>>> extract_host("evilcorp.com:80")
("evilcorp.com", "", ":80")
>>> extract_host("http://evilcorp.com:80/asdf.php?a=b")
("evilcorp.com", "http://", ":80/asdf.php?a=b")
>>> extract_host("bob@evilcorp.com")
("evilcorp.com", "bob@", "")
>>> extract_host("[dead::beef]:22")
("dead::beef", "[", "]:22")
>>> extract_host("ftp://username:password@my-ftp.com/my-file.csv")
(
"my-ftp.com",
"ftp://username:password@",
"/my-file.csv",
)
Source code in bbot/core/helpers/misc.py
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 |
|
extract_params_json
extract_params_json(json_data, compare_mode='getparam')
Extracts key-value pairs from a JSON object and returns them as a set of tuples. Used by the paramminer_headers
module.
Parameters:
-
json_data
(str
) –JSON-formatted string containing key-value pairs.
Returns:
-
set
–A set of tuples containing the keys and their corresponding values present in the JSON object.
Examples:
>>> extract_params_json('{"a": 1, "b": {"c": 2}}')
{('a', 1), ('b', {'c': 2}), ('c', 2)}
Source code in bbot/core/helpers/misc.py
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 |
|
extract_params_xml
extract_params_xml(xml_data, compare_mode='getparam')
Extracts tags and their text values from an XML object and returns them as a set of tuples.
Parameters:
-
xml_data
(str
) –XML-formatted string containing elements.
Returns:
-
set
–A set of tuples containing the tags and their corresponding sanitized text values present in the XML object.
Examples:
>>> extract_params_xml('<root><child1><child2>value</child2></child1></root>')
{('root', None), ('child1', None), ('child2', 'value')}
Source code in bbot/core/helpers/misc.py
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 |
|
extract_words
extract_words(data, acronyms=True, wordninja=True, model=None, max_length=100, word_regexes=None)
Intelligently extracts words from given data.
This function uses regular expressions and optionally wordninja to extract words from a given text string. Thanks to wordninja it can handle concatenated words intelligently.
Parameters:
-
data
(str
) –The data from which words are to be extracted.
-
acronyms
(bool
, default:True
) –Whether to include acronyms. Defaults to True.
-
wordninja
(bool
, default:True
) –Whether to use the wordninja library to split concatenated words. Defaults to True.
-
model
(object
, default:None
) –A custom wordninja model for special types of data such as DNS names.
-
max_length
(int
, default:100
) –Maximum length for a word to be included. Defaults to 100.
-
word_regexes
(list
, default:None
) –A list of compiled regular expression objects for word extraction. Defaults to None.
Returns:
-
set
–A set of extracted words.
Examples:
>>> extract_words('blacklanternsecurity')
{'black', 'lantern', 'security', 'bls', 'blacklanternsecurity'}
Source code in bbot/core/helpers/misc.py
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 |
|
filesize
filesize(f)
Get the file size of a given file.
This function takes a file path as an argument and returns its size in bytes. If the path does not point to a file, the function returns 0.
Parameters:
Returns:
-
int
–The size of the file in bytes, or 0 if the path does not point to a file.
Examples:
>>> filesize("/path/to/file.txt")
1024
Source code in bbot/core/helpers/misc.py
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 |
|
filter_dict
filter_dict(d, *key_names, fuzzy=False, exclude_keys=None, _prev_key=None)
Recursively filter a dictionary based on key names.
Parameters:
-
d
(dict
) –The input dictionary.
-
*key_names
–Names of keys to filter for.
-
fuzzy
(bool
, default:False
) –Whether to perform fuzzy matching on keys.
-
exclude_keys
((list, None)
, default:None
) –List of keys to be excluded from the final dict.
-
_prev_key
((str, None)
, default:None
) –For internal recursive use; the previous key in the hierarchy.
Returns:
-
dict
–A dictionary containing only the keys specified in key_names.
Examples:
>>> filter_dict({"key1": "test", "key2": "asdf"}, "key2")
{"key2": "asdf"}
>>> filter_dict({"key1": "test", "key2": {"key3": "asdf"}}, "key1", "key3", exclude_keys="key2")
{'key1': 'test'}
Source code in bbot/core/helpers/misc.py
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 |
|
gen_numbers
gen_numbers(n, padding=2)
Generates numbers with variable padding and returns them as a set of strings.
Parameters:
-
n
(int
) –The upper limit of numbers to generate, exclusive.
-
padding
(int
, default:2
) –The maximum number of digits to pad the numbers with. Defaults to 2.
Returns:
-
set
–A set of string representations of numbers with varying degrees of padding.
Examples:
>>> gen_numbers(5)
{'0', '00', '01', '02', '03', '04', '1', '2', '3', '4'}
>>> gen_numbers(3, padding=3)
{'0', '00', '000', '001', '002', '01', '02', '1', '2'}
>>> gen_numbers(5, padding=1)
{'0', '1', '2', '3', '4'}
Source code in bbot/core/helpers/misc.py
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 |
|
get_closest_match
get_closest_match(s, choices, msg=None)
Finds the closest match from a list of choices for a given string.
This function is particularly useful for CLI applications where you want to validate flags or modules.
Parameters:
-
s
(str
) –The string for which to find the closest match.
-
choices
(list
) –A list of strings to compare against.
-
msg
(str
, default:None
) –Additional message to prepend in the warning message. Defaults to None.
-
loglevel
(str
) –The log level to use for the warning message. Defaults to "HUGEWARNING".
-
exitcode
(int
) –The exit code to use when exiting the program. Defaults to 2.
Examples:
>>> get_closest_match("some_module", ["some_mod", "some_other_mod"], msg="module")
# Output: Could not find module "some_module". Did you mean "some_mod"?
Source code in bbot/core/helpers/misc.py
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 |
|
get_exception_chain
get_exception_chain(e)
Retrieves the full chain of exceptions leading to the given exception.
Parameters:
-
e
(BaseException
) –The exception for which to get the chain.
Returns:
-
–
list[BaseException]: List of exceptions in the chain, from the given exception back to the root cause.
Examples:
>>> try:
... raise ValueError("This is a value error")
... except ValueError as e:
... exc_chain = get_exception_chain(e)
... for exc in exc_chain:
... print(exc)
This is a value error
Source code in bbot/core/helpers/misc.py
2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 |
|
get_file_extension
get_file_extension(s)
Extracts the file extension from a given string representing a URL or file path.
Parameters:
-
s
(str
) –The string from which to extract the file extension.
Returns:
-
str
–The file extension, or an empty string if no extension is found.
Examples:
>>> get_file_extension("https://evilcorp.com/api/test.php")
"php"
>>> get_file_extension("/etc/test.conf")
"conf"
>>> get_file_extension("/etc/passwd")
""
Source code in bbot/core/helpers/misc.py
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 |
|
get_get_params
get_get_params(url)
Extract the query parameters from the given URL as a dictionary.
Parameters:
-
url
(Union[str, ParseResult]
) –The URL from which to extract query parameters.
Returns:
-
–
Dict[str, List[str]]: A dictionary containing the query parameters and their values.
Examples:
>>> get_get_params('https://www.evilcorp.com?foo=1&bar=2')
{'foo': ['1'], 'bar': ['2']}
>>> get_get_params('https://www.evilcorp.com?foo=1&foo=2')
{'foo': ['1', '2']}
Source code in bbot/core/helpers/url.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
|
get_keys_in_dot_syntax
get_keys_in_dot_syntax(config)
Retrieve all keys in an OmegaConf configuration in dot notation.
This function converts an OmegaConf configuration into a list of keys represented in dot notation.
Parameters:
-
config
(DictConfig
) –The OmegaConf configuration object.
Returns:
-
–
List[str]: A list of keys in dot notation.
Examples:
>>> config = OmegaConf.create({
... "web": {
... "test": True
... },
... "db": {
... "host": "localhost",
... "port": 5432
... }
... })
>>> get_keys_in_dot_syntax(config)
['web.test', 'db.host', 'db.port']
Source code in bbot/core/helpers/misc.py
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 |
|
get_size
get_size(obj, max_depth=5, seen=None)
Roughly estimate the memory footprint of a Python object using recursion.
Parameters:
-
obj
(any
) –The object whose size is to be determined.
-
max_depth
(int
, default:5
) –Maximum depth to which nested objects will be inspected. Defaults to 5.
-
seen
(set
, default:None
) –Objects that have already been accounted for, to avoid loops.
Returns:
-
int
–Approximate memory footprint of the object in bytes.
Examples:
>>> get_size(my_list)
4200
>>> get_size(my_dict, max_depth=3)
8400
Source code in bbot/core/helpers/misc.py
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 |
|
get_traceback_details
get_traceback_details(e)
Retrieves detailed information from the traceback of an exception.
Parameters:
-
e
(BaseException
) –The exception for which to get traceback details.
Returns:
-
tuple
–A tuple containing filename (str), line number (int), and function name (str) where the exception was raised.
Examples:
>>> try:
... raise ValueError("This is a value error")
... except ValueError as e:
... filename, lineno, funcname = get_traceback_details(e)
... print(f"File: {filename}, Line: {lineno}, Function: {funcname}")
File: <stdin>, Line: 2, Function: <module>
Source code in bbot/core/helpers/misc.py
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 |
|
grouper
grouper(iterable, n)
Grouper groups an iterable into chunks of a given size.
Parameters:
-
iterable
(iterable
) –The iterable to be chunked.
-
n
(int
) –The size of each chunk.
Returns:
-
iterator
–An iterator that produces lists of elements from the original iterable, each of length
n
or less.
Examples:
>>> list(grouper('ABCDEFG', 3))
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
Source code in bbot/core/helpers/misc.py
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 |
|
hash_url
hash_url(url)
Hashes a URL for the purpose of cleaning or collapsing similar URLs.
Parameters:
-
url
(str
) –The URL to be hashed.
Returns:
-
int
–The hash value of the cleaned URL.
Examples:
>>> hash_url('https://www.evilcorp.com')
-7448777882396416944
>>> hash_url('https://www.evilcorp.com/page/1')
-8101275613229735915
>>> hash_url('https://www.evilcorp.com/page/2')
-8101275613229735915
Source code in bbot/core/helpers/url.py
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
|
human_timedelta
human_timedelta(d)
Convert a TimeDelta object into a human-readable string.
This function takes a datetime.timedelta object and converts it into a string format that is easier to read and understand.
Parameters:
-
d
(timedelta
) –The TimeDelta object to convert.
Returns:
-
str
–A string representation of the TimeDelta object in human-readable form.
Examples:
>>> from datetime import datetime
>>>
>>> start_time = datetime.now()
>>> end_time = datetime.now()
>>> elapsed_time = end_time - start_time
>>> human_timedelta(elapsed_time)
'2 hours, 30 minutes, 15 seconds'
Source code in bbot/core/helpers/misc.py
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 |
|
human_to_bytes
human_to_bytes(filesize)
Convert a human-readable file size string to its bytes equivalent.
This function takes a human-readable file size string, such as "2.5GB", and converts it to its equivalent number of bytes.
Parameters:
Returns:
-
int
–The number of bytes equivalent to the input human-readable file size.
Raises:
-
ValueError
–If the input string cannot be converted to bytes.
Examples:
>>> human_to_bytes("23.23gb")
24943022571
Source code in bbot/core/helpers/misc.py
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 |
|
in_exception_chain
in_exception_chain(e, exc_types)
Given an Exception and a list of Exception types, returns whether any of the specified types are contained anywhere in the Exception chain.
Parameters:
-
e
(BaseException
) –The exception to check
-
exc_types
(list[Exception]
) –Exception types to consider intentional cancellations. Default is KeyboardInterrupt
Returns:
-
bool
–Whether the error is the result of an intentional cancellaion
Examples:
>>> try:
... raise ValueError("This is a value error")
... except Exception as e:
... if not in_exception_chain(e, (KeyboardInterrupt, asyncio.CancelledError)):
... raise
Source code in bbot/core/helpers/misc.py
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 |
|
integer_to_ordinal
integer_to_ordinal(n)
Convert an integer to its ordinal representation.
Parameters:
-
n
(int
) –The integer to convert.
Returns:
-
str
–The ordinal representation of the integer.
Examples:
>>> integer_to_ordinal(1)
'1st'
>>> integer_to_ordinal(2)
'2nd'
>>> integer_to_ordinal(3)
'3rd'
>>> integer_to_ordinal(11)
'11th'
>>> integer_to_ordinal(21)
'21st'
>>> integer_to_ordinal(101)
'101st'
Source code in bbot/core/helpers/misc.py
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 |
|
ip_network_parents
ip_network_parents(i, include_self=False)
Generates all parent IP networks for a given IP address or network, optionally including the network itself.
Parameters:
-
i
(str or IPv4Network / IPv6Network
) –The IP address or network to find parents for.
-
include_self
(bool
, default:False
) –Whether to include the network itself in the result. Default is False.
Yields:
-
–
ipaddress.IPv4Network or ipaddress.IPv6Network: Parent IP networks in descending order of prefix length.
Examples:
>>> list(ip_network_parents("192.168.1.1"))
[ipaddress.IPv4Network('192.168.1.0/31'), ipaddress.IPv4Network('192.168.1.0/30'), ... , ipaddress.IPv4Network('0.0.0.0/0')]
Notes
- Utilizes Python's built-in
ipaddress
module for network operations.
Source code in bbot/core/helpers/misc.py
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 |
|
is_async_function
is_async_function(f)
Check if a given function is an asynchronous function.
Parameters:
-
f
(function
) –The function to check.
Returns:
-
bool
–True if the function is asynchronous, False otherwise.
Examples:
>>> async def foo():
... pass
>>> is_async_function(foo)
True
Source code in bbot/core/helpers/misc.py
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 |
|
is_dns_name
is_dns_name(d)
Determines if the given string is a valid DNS name.
Parameters:
-
d
(str
) –The string to be checked.
Returns:
-
bool
–True if the string is a valid DNS name, False otherwise.
Examples:
>>> is_dns_name('www.example.com')
True
>>> is_dns_name('localhost')
True
>>> is_dns_name('192.168.1.1')
False
Source code in bbot/core/helpers/misc.py
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 |
|
is_domain
is_domain(d)
Check if the given input represents a domain without subdomains.
This function takes an input string d
and returns True if it represents a domain without any subdomains.
Otherwise, it returns False.
Parameters:
-
d
(str
) –The input string containing the domain.
Returns:
-
bool
–True if the input is a domain without subdomains, False otherwise.
Examples:
>>> is_domain("evilcorp.co.uk")
True
>>> is_domain("www.evilcorp.co.uk")
False
Notes
- Port, if present in input, is ignored.
Source code in bbot/core/helpers/misc.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
|
is_file
is_file(f)
Check if a path points to a file.
Parameters:
-
f
(str
) –Path to the file.
Returns:
-
bool
–True if the path is a file, False otherwise.
Examples:
>>> is_file("/etc/passwd")
True
>>> is_file("/nonexistent")
False
Source code in bbot/core/helpers/misc.py
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 |
|
is_ip
is_ip(d, version=None, include_network=False)
Checks if the given string or object represents a valid IP address.
Parameters:
-
d
(str or IPvXAddress
) –The IP address to check.
-
include_network
(bool
, default:False
) –Whether to include network types (IPv4Network or IPv6Network). Defaults to False.
-
version
(int
, default:None
) –The IP version to validate (4 or 6). Default is None.
Returns:
-
bool
–True if the string or object is a valid IP address, False otherwise.
Examples:
>>> is_ip('192.168.1.1')
True
>>> is_ip('bad::c0de', version=6)
True
>>> is_ip('bad::c0de', version=4)
False
>>> is_ip('evilcorp.com')
False
Source code in bbot/core/helpers/misc.py
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 |
|
is_ip_type
is_ip_type(i, network=None)
Checks if the given object is an instance of an IPv4 or IPv6 type from the ipaddress module.
Parameters:
-
i
(_BaseV4 or _BaseV6
) –The IP object to check.
-
network
(bool
, default:None
) –Whether to restrict the check to network types (IPv4Network or IPv6Network). Defaults to False.
Returns:
-
bool
–True if the object is an instance of ipaddress._BaseV4 or ipaddress._BaseV6, False otherwise.
Examples:
>>> is_ip_type(ipaddress.IPv6Address('dead::beef'))
True
>>> is_ip_type(ipaddress.IPv4Network('192.168.1.0/24'))
True
>>> is_ip_type("192.168.1.0/24")
False
Source code in bbot/core/helpers/misc.py
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 |
|
is_port
is_port(p)
Checks if the given string represents a valid port number.
Parameters:
Returns:
-
bool
–True if the port number is valid, False otherwise.
Examples:
>>> is_port('80')
True
>>> is_port('70000')
False
Source code in bbot/core/helpers/misc.py
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
|
is_printable
is_printable(s)
Check if a string is printable
Source code in bbot/core/helpers/misc.py
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 |
|
is_ptr
is_ptr(d)
Check if the given input represents a PTR record domain.
This function takes an input string d
and returns True if it matches the PTR record format.
Otherwise, it returns False.
Parameters:
-
d
(str
) –The input string potentially representing a PTR record domain.
Returns:
-
bool
–True if the input matches PTR record format, False otherwise.
Examples:
>>> is_ptr("wsc-11-22-33-44.evilcorp.com")
True
>>> is_ptr("www2.evilcorp.com")
False
Source code in bbot/core/helpers/misc.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
|
is_subdomain
is_subdomain(d)
Check if the given input represents a subdomain.
This function takes an input string d
and returns True if it represents a subdomain.
Otherwise, it returns False.
Parameters:
-
d
(str
) –The input string containing the domain or subdomain.
Returns:
-
bool
–True if the input is a subdomain, False otherwise.
Examples:
>>> is_subdomain("www.evilcorp.co.uk")
True
>>> is_subdomain("evilcorp.co.uk")
False
Notes
- Port, if present in input, is ignored.
Source code in bbot/core/helpers/misc.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
|
is_uri
is_uri(u, return_scheme=False)
Check if the given input represents a URI and optionally return its scheme.
This function takes an input string u
and returns True if it matches a URI format.
When return_scheme
is True, it returns the URI scheme instead of a boolean.
Parameters:
-
u
(str
) –The input string potentially representing a URI.
-
return_scheme
(bool
, default:False
) –Whether to return the URI scheme. Defaults to False.
Returns:
-
–
Union[bool, str]: True if the input matches a URI format; the URI scheme if
return_scheme
is True.
Examples:
>>> is_uri("http://evilcorp.com")
True
>>> is_uri("ftp://evilcorp.com")
True
>>> is_uri("evilcorp.com")
False
>>> is_uri("ftp://evilcorp.com", return_scheme=True)
"ftp"
Source code in bbot/core/helpers/misc.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
|
is_url
is_url(u)
Check if the given input represents a valid URL.
This function takes an input string u
and returns True if it matches any of the predefined URL formats.
Otherwise, it returns False.
Parameters:
-
u
(str
) –The input string potentially representing a URL.
Returns:
-
bool
–True if the input matches a valid URL format, False otherwise.
Examples:
>>> is_url("https://evilcorp.com")
True
>>> is_url("not-a-url")
False
Source code in bbot/core/helpers/misc.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
|
kill_children
kill_children(parent_pid=None, sig=None)
Forgive me father for I have sinned
Source code in bbot/core/helpers/misc.py
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 |
|
latest_mtime
latest_mtime(d)
Get the latest modified time of any file or sub-directory in a given directory.
This function takes a directory path as an argument and returns the latest modified time of any contained file or directory, recursively. It's useful for sorting directories by modified time for cleanup or other purposes.
Parameters:
Returns:
-
float
–The latest modified time in Unix timestamp format.
Examples:
>>> latest_mtime("~/.bbot/scans/mushy_susan")
1659016928.2848816
Source code in bbot/core/helpers/misc.py
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 |
|
list_files
list_files(directory, filter=lambda x: True)
Lists files in a given directory that meet a specified filter condition.
Parameters:
-
directory
(str
) –The directory where to list files.
-
filter
(callable
, default:lambda x: True
) –A function to filter the files. Defaults to a lambda function that returns True for all files.
Yields:
-
Path
–A Path object for each file that meets the filter condition.
Examples:
>>> list(list_files("/tmp/test"))
[Path('/tmp/test/file1.py'), Path('/tmp/test/file2.txt')]
>>> list(list_files("/tmp/test"), filter=lambda f: f.suffix == ".py")
[Path('/tmp/test/file1.py')]
Source code in bbot/core/helpers/misc.py
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 |
|
make_date
make_date(d=None, microseconds=False)
Generates a string representation of the current date and time, with optional microsecond precision.
Parameters:
-
d
(datetime
, default:None
) –A datetime object to convert. Defaults to the current date and time.
-
microseconds
(bool
, default:False
) –Whether to include microseconds. Defaults to False.
Returns:
-
str
–A string representation of the date and time, formatted as YYYYMMDD_HHMM_SS or YYYYMMDD_HHMM_SSFFFFFF if microseconds are included.
Examples:
>>> make_date()
"20220707_1325_50"
>>> make_date(microseconds=True)
"20220707_1330_35167617"
Source code in bbot/core/helpers/misc.py
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 |
|
make_ip_type
make_ip_type(s)
Convert a string to its corresponding IP address or network type.
This function attempts to convert the input string s
into either an IPv4 or IPv6 address object,
or an IPv4 or IPv6 network object. If none of these conversions are possible, the original string is returned.
Parameters:
-
s
(str
) –The input string to be converted.
Returns:
-
–
Union[IPv4Address, IPv6Address, IPv4Network, IPv6Network, str]: The converted object or original string.
Examples:
>>> make_ip_type("dead::beef")
IPv6Address('dead::beef')
>>> make_ip_type("192.168.1.0/24")
IPv4Network('192.168.1.0/24')
>>> make_ip_type("evilcorp.com")
'evilcorp.com'
Source code in bbot/core/helpers/misc.py
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 |
|
make_netloc
make_netloc(host, port=None)
Constructs a network location string from a given host and port.
Parameters:
-
host
(str
) –The hostname or IP address.
-
port
(int
, default:None
) –The port number. If None, the port is omitted.
Returns:
-
str
–A network location string in the form 'host' or 'host:port'.
Examples:
>>> make_netloc("192.168.1.1", None)
"192.168.1.1"
>>> make_netloc("192.168.1.1", 443)
"192.168.1.1:443"
>>> make_netloc("evilcorp.com", 80)
"evilcorp.com:80"
>>> make_netloc("dead::beef", None)
"[dead::beef]"
>>> make_netloc("dead::beef", 443)
"[dead::beef]:443"
Source code in bbot/core/helpers/misc.py
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 |
|
make_table
make_table(rows, header, **kwargs)
Generate a formatted table from the given rows and headers.
This function uses the tabulate
package to generate a table with formatting options.
It can accept various input formats and table styles, which can be customized using optional arguments.
Parameters:
-
*args
–Positional arguments to be passed to
tabulate.tabulate
. -
**kwargs
–Keyword arguments to customize table formatting. - tablefmt (str, optional): Table format. Default is 'grid'. - disable_numparse (bool, optional): Disable automatic number parsing. Default is True. - maxcolwidths (int, optional): Maximum column width. Default is 40.
Returns:
-
str
–A string representing the formatted table.
Examples:
>>> print(make_table([["row1", "row1"], ["row2", "row2"]], ["header1", "header2"]))
+-----------+-----------+
| header1 | header2 |
+===========+===========+
| row1 | row1 |
+-----------+-----------+
| row2 | row2 |
+-----------+-----------+
Source code in bbot/core/helpers/misc.py
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 |
|
memory_status
memory_status()
Return statistics on system memory consumption.
The function returns a psutil
named tuple that contains statistics on
system virtual memory usage, such as total memory, used memory, available
memory, and more.
Returns:
-
–
psutil._pslinux.svmem: A named tuple representing various statistics about system virtual memory usage.
Examples:
>>> mem = memory_status()
>>> mem.available
13195399168
>>> mem = memory_status()
>>> mem.percent
79.0
Source code in bbot/core/helpers/misc.py
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 |
|
mkdir
mkdir(path, check_writable=True, raise_error=True)
Creates a directory and optionally checks if it's writable.
Parameters:
-
path
(str or Path
) –The directory to create.
-
check_writable
(bool
, default:True
) –Whether to check if the directory is writable. Default is True.
-
raise_error
(bool
, default:True
) –Whether to raise an error if the directory creation fails. Default is True.
Returns:
-
bool
–True if the directory is successfully created (and writable, if check_writable=True); otherwise False.
Raises:
-
DirectoryCreationError
–Raised if the directory cannot be created and
raise_error=True
.
Examples:
>>> mkdir("/tmp/new_dir")
True
>>> mkdir("/restricted_dir", check_writable=False, raise_error=False)
False
Source code in bbot/core/helpers/misc.py
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 |
|
os_platform
os_platform()
Return the OS platform of the current system.
This function fetches and returns the OS type where the code is being executed. It converts the platform identifier to lowercase.
Returns:
-
str
–A string representing the OS platform, such as "linux", "darwin", or "windows".
Examples:
>>> os_platform()
'linux'
Source code in bbot/core/helpers/misc.py
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 |
|
os_platform_friendly
os_platform_friendly()
Return a human-friendly OS platform string, suitable for golang release binaries.
This function fetches the OS platform and modifies it to a more human-readable format if necessary. Specifically, it changes "darwin" to "macOS".
Returns:
-
str
–A string representing the human-friendly OS platform, such as "macOS", "linux", or "windows".
Examples:
>>> os_platform_friendly()
'macOS'
Source code in bbot/core/helpers/misc.py
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 |
|
param_type
param_type(p)
Evaluates the type of the given parameter.
Parameters:
-
p
(str
) –The parameter whose type is to be evaluated.
Returns:
-
int
–An integer representing the type of parameter. - 1: Integer - 2: UUID - 3: Other
Examples:
>>> param_type('123')
1
>>> param_type('550e8400-e29b-41d4-a716-446655440000')
2
>>> param_type('abc')
3
Source code in bbot/core/helpers/url.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
|
parent_domain
parent_domain(d)
Retrieve the parent domain of a given subdomain string.
This function takes an input string d
representing a subdomain and returns its parent domain.
If the input does not represent a subdomain, it returns the input as is.
Parameters:
-
d
(str
) –The input string representing a subdomain or domain.
Returns:
-
str
–The parent domain of the subdomain, or the original input if it is not a subdomain.
Examples:
>>> parent_domain("www.internal.evilcorp.co.uk")
"internal.evilcorp.co.uk"
>>> parent_domain("www.internal.evilcorp.co.uk:8080")
"internal.evilcorp.co.uk:8080"
>>> parent_domain("www.evilcorp.co.uk")
"evilcorp.co.uk"
>>> parent_domain("evilcorp.co.uk")
"evilcorp.co.uk"
Notes
- Port, if present in input, is preserved in the output.
Source code in bbot/core/helpers/misc.py
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
|
parent_url
parent_url(u)
Retrieve the parent URL of a given URL.
This function takes an input string u
representing a URL and returns its parent URL.
If the input URL does not have a parent (i.e., it's already the top-level), it returns None.
Parameters:
-
u
(str
) –The input string representing a URL.
Returns:
-
–
Union[str, None]: The parent URL of the input URL, or None if it has no parent.
Examples:
>>> parent_url("https://evilcorp.com/sub/path/")
"https://evilcorp.com/sub/"
>>> parent_url("https://evilcorp.com/")
None
Notes
- Only the path component of the URL is modified.
- All other components like scheme, netloc, query, and fragment are preserved.
Source code in bbot/core/helpers/misc.py
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
|
parse_port_string
parse_port_string(port_string)
Parses a string containing ports and port ranges into a list of individual ports.
Parameters:
-
port_string
(str
) –The string containing individual ports and port ranges separated by commas.
Returns:
-
list
–A list of individual ports parsed from the input string.
Raises:
-
ValueError
–If the input string contains invalid ports or port ranges.
Examples:
>>> parse_port_string("22,80,1000-1002")
[22, 80, 1000, 1001, 1002]
>>> parse_port_string("1-2,3-5")
[1, 2, 3, 4, 5]
>>> parse_port_string("invalid")
ValueError: Invalid port or port range: invalid
Source code in bbot/core/helpers/misc.py
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 |
|
parse_url
parse_url(url)
Parse the given URL string or ParseResult object and return a ParseResult.
This function checks if the input is already a ParseResult object. If it is,
it returns the object as-is. Otherwise, it parses the given URL string using
urlparse
.
Parameters:
-
url
(Union[str, ParseResult]
) –The URL string or ParseResult object to be parsed.
Returns:
-
ParseResult
–A named 6-tuple that contains the components of a URL.
Examples:
>>> parse_url('https://www.evilcorp.com')
ParseResult(scheme='https', netloc='www.evilcorp.com', path='', params='', query='', fragment='')
Source code in bbot/core/helpers/url.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
rand_string
rand_string(length=10, digits=True, numeric_only=False)
Generates a random string of specified length.
Parameters:
-
length
(int
, default:10
) –The length of the random string. Defaults to 10.
-
digits
(bool
, default:True
) –Whether to include digits in the string. Defaults to True.
-
numeric_only
(bool
, default:False
) –Whether to generate a numeric-only string. Defaults to False.
Returns:
-
str
–A random string of the specified length.
Examples:
>>> rand_string()
'c4hp4i9jzx'
>>> rand_string(20)
'ap4rsdtg5iw7ey7y3oa5'
>>> rand_string(30, digits=False)
'xdmyxtglqfzqktngkesyulwbfrihva'
>>> rand_string(15, numeric_only=True)
'934857349857395'
Source code in bbot/core/helpers/misc.py
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 |
|
read_file
read_file(filename)
Reads a file line by line and yields each line without line breaks.
Parameters:
Yields:
-
str
–A line from the file without the trailing line break.
Examples:
>>> for line in read_file("/tmp/file.txt"):
... print(line)
file_line1
file_line2
file_line3
Source code in bbot/core/helpers/misc.py
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 |
|
recursive_decode
recursive_decode(data, max_depth=5)
Recursively decodes doubly or triply-encoded strings to their original form.
Supports both URL-encoding and backslash-escapes (including unicode)
Parameters:
-
data
(str
) –The data to decode.
-
max_depth
(int
, default:5
) –Maximum recursion depth for decoding. Defaults to 5.
Returns:
-
str
–The decoded string.
Examples:
>>> recursive_decode("Hello%20world%21")
"Hello world!"
>>> recursive_decode("Hello%20%5Cu041f%5Cu0440%5Cu0438%5Cu0432%5Cu0435%5Cu0442")
"Hello Привет"
>>> recursive_dcode("%5Cu0020%5Cu041f%5Cu0440%5Cu0438%5Cu0432%5Cu0435%5Cu0442%5Cu0021")
" Привет!"
Source code in bbot/core/helpers/misc.py
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 |
|
rm_at_exit
rm_at_exit(path)
Registers a file to be automatically deleted when the program exits.
Parameters:
Examples:
>>> rm_at_exit("/tmp/test/file1.txt")
Source code in bbot/core/helpers/misc.py
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 |
|
rm_rf
rm_rf(f)
Recursively delete a directory
Parameters:
Examples:
>>> rm_rf("/tmp/httpx98323849")
Source code in bbot/core/helpers/misc.py
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 |
|
safe_format
safe_format(s, **kwargs)
Format string while ignoring unused keys (prevents KeyError)
Source code in bbot/core/helpers/misc.py
2830 2831 2832 2833 2834 |
|
search_dict_by_key
search_dict_by_key(key, d)
Search a nested dictionary or list of dictionaries by a key and yield all matching values.
Parameters:
-
key
(str
) –The key to search for.
-
d
(Union[dict, list]
) –The dictionary or list of dictionaries to search.
Yields:
-
Any
–Yields all values that match the provided key.
Examples:
>>> d = {'a': 1, 'b': {'c': 2, 'a': 3}, 'd': [{'a': 4}, {'e': 5}]}
>>> list(search_dict_by_key('a', d))
[1, 3, 4]
Source code in bbot/core/helpers/misc.py
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 |
|
search_dict_values
search_dict_values(d, *regexes)
Recursively search a dictionary's values based on provided regex patterns.
Parameters:
-
d
(Union[dict, list, str]
) –The dictionary, list, or string to search.
-
*regexes
–Arbitrary number of compiled regex patterns.
Returns:
-
Generator
–Yields matching values based on the provided regex patterns.
Examples:
>>> dict_to_search = {
... "key1": {
... "key2": [
... {
... "key3": "A URL: https://www.evilcorp.com"
... }
... ]
... }
... }
>>> url_regexes = re.compile(r'https?://[^\s<>"]+|www\.[^\s<>"]+')
>>> list(search_dict_values(dict_to_search, url_regexes))
["https://www.evilcorp.com"]
Source code in bbot/core/helpers/misc.py
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 |
|
search_format_dict
search_format_dict(d, **kwargs)
Recursively format string values in a dictionary or list using the provided keyword arguments.
Parameters:
-
d
(Union[dict, list, str]
) –The dictionary, list, or string to format.
-
**kwargs
–Arbitrary keyword arguments used for string formatting.
Returns:
-
–
Union[dict, list, str]: The formatted dictionary, list, or string.
Examples:
>>> search_format_dict({"test": "#{name} is awesome"}, name="keanu")
{"test": "keanu is awesome"}
Source code in bbot/core/helpers/misc.py
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 |
|
sha1
sha1(data)
Computes the SHA-1 hash of the given data.
Parameters:
-
data
(str or dict
) –The data to hash. If a dictionary, it is first converted to a JSON string with sorted keys.
Returns:
-
–
hashlib.Hash: SHA-1 hash object of the input data.
Examples:
>>> sha1("asdf").hexdigest()
'3da541559918a808c2402bba5012f6c60b27661c'
Source code in bbot/core/helpers/misc.py
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 |
|
smart_decode
smart_decode(data)
Decodes the input data to a UTF-8 string, silently ignoring errors.
Parameters:
Returns:
-
str
–The decoded string.
Examples:
>>> smart_decode(b"asdf")
"asdf"
>>> smart_decode("asdf")
"asdf"
Source code in bbot/core/helpers/misc.py
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 |
|
smart_decode_punycode
smart_decode_punycode(text: str) -> str
xn--eckwd4c7c.xn--zckzah --> ドメイン.テスト
Source code in bbot/core/helpers/misc.py
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 |
|
smart_encode
smart_encode(data)
Encodes the input data to bytes using UTF-8 encoding, silently ignoring errors.
Parameters:
Returns:
-
bytes
–The encoded bytes.
Examples:
>>> smart_encode("asdf")
b"asdf"
>>> smart_encode(b"asdf")
b"asdf"
Source code in bbot/core/helpers/misc.py
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
|
smart_encode_punycode
smart_encode_punycode(text: str) -> str
ドメイン.テスト --> xn--eckwd4c7c.xn--zckzah
Source code in bbot/core/helpers/misc.py
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 |
|
split_domain
split_domain(hostname)
Splits the hostname into its subdomain and registered domain components.
Parameters:
-
hostname
(str
) –The full hostname to be split.
Returns:
-
tuple
–A tuple containing the subdomain and registered domain.
Examples:
>>> split_domain("www.internal.evilcorp.co.uk")
("www.internal", "evilcorp.co.uk")
Notes
- Utilizes the
tldextract
function to first break down the hostname.
Source code in bbot/core/helpers/misc.py
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 |
|
split_host_port
split_host_port(d)
Parse a string containing a host and port into a tuple.
This function takes an input string d
and returns a tuple containing the host and port.
The host is converted to its appropriate IP address type if possible. The port is inferred
based on the scheme if not provided.
Parameters:
-
d
(str
) –The input string containing the host and possibly the port.
Returns:
-
–
Tuple[Union[IPv4Address, IPv6Address, str], Optional[int]]: Tuple containing the host and port.
Examples:
>>> split_host_port("evilcorp.com:443")
("evilcorp.com", 443)
>>> split_host_port("192.168.1.1:443")
(IPv4Address('192.168.1.1'), 443)
>>> split_host_port("[dead::beef]:443")
(IPv6Address('dead::beef'), 443)
Notes
- If port is not provided, it is inferred based on the scheme:
- For "https" and "wss", port 443 is used.
- For "http" and "ws", port 80 is used.
Source code in bbot/core/helpers/misc.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
|
split_list
split_list(alist, wanted_parts=2)
Splits a list into a specified number of approximately equal parts.
Parameters:
-
alist
(list
) –The list to be split.
-
wanted_parts
(int
, default:2
) –The number of parts to split the list into.
Returns:
-
list
–A list of lists, each containing a portion of the original list.
Examples:
>>> split_list([1, 2, 3, 4, 5])
[[1, 2], [3, 4, 5]]
Source code in bbot/core/helpers/misc.py
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 |
|
str_or_file
str_or_file(s)
Reads a string or file and yields its content line-by-line.
This function tries to open the given string s
as a file and yields its lines.
If it fails to open s
as a file, it treats s
as a regular string and yields it as is.
Parameters:
-
s
(str
) –The string or file path to read.
Yields:
-
str
–Either lines from the file or the original string.
Examples:
>>> list(str_or_file("file.txt"))
['file_line1', 'file_line2', 'file_line3']
>>> list(str_or_file("not_a_file"))
['not_a_file']
Source code in bbot/core/helpers/misc.py
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 |
|
subdomain_depth
subdomain_depth(d)
Calculate the depth of subdomains within a given domain name.
Parameters:
-
d
(str
) –The domain name to analyze.
Returns:
-
int
–The depth of the subdomain. For example, a hostname "5.4.3.2.1.evilcorp.com"
-
–
has a subdomain depth of 5.
Source code in bbot/core/helpers/misc.py
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 |
|
swap_status
swap_status()
Return statistics on swap memory consumption.
The function returns a psutil
named tuple that contains statistics on
system swap memory usage, such as total swap, used swap, free swap, and more.
Returns:
-
–
psutil._common.sswap: A named tuple representing various statistics about system swap memory usage.
Examples:
>>> swap = swap_status()
>>> swap.total
4294967296
>>> swap = swap_status()
>>> swap.used
2097152
Source code in bbot/core/helpers/misc.py
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 |
|
tagify
tagify(s, delimiter=None, maxlen=None)
Sanitize a string into a tag-friendly format.
Converts a given string to lowercase and replaces all characters not matching [a-z0-9] with hyphens. Optionally truncates the result to 'maxlen' characters.
Parameters:
-
s
(str
) –The input string to sanitize.
-
maxlen
(int
, default:None
) –The maximum length for the tag. Defaults to None.
Returns:
-
str
–A sanitized, tag-friendly string.
Examples:
>>> tagify("HTTP Web Title")
'http-web-title'
>>> tagify("HTTP Web Title", maxlen=8)
'http-web'
Source code in bbot/core/helpers/misc.py
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 |
|
tldextract
tldextract(data)
Extracts the subdomain, domain, and suffix from a URL string.
Parameters:
-
data
(str
) –The URL string to be processed.
Returns:
-
ExtractResult
–A named tuple containing the subdomain, domain, and suffix.
Examples:
>>> tldextract("www.evilcorp.co.uk")
ExtractResult(subdomain='www', domain='evilcorp', suffix='co.uk')
Notes
- Utilizes
smart_decode
to preprocess the data. - Makes use of the
tldextract
library for extraction.
Source code in bbot/core/helpers/misc.py
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 |
|
top_tcp_ports
top_tcp_ports(n, as_string=False)
Returns the top n TCP ports as evaluated by nmap
Source code in bbot/core/helpers/misc.py
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 |
|
truncate_filename
truncate_filename(file_path, max_length=255)
Truncate the filename while preserving the file extension to ensure the total path length does not exceed the maximum length.
Parameters:
-
file_path
(str
) –The original file path.
-
max_length
(int
, default:255
) –The maximum allowed length for the total path. Default is 255.
Returns:
-
–
pathlib.Path: A new Path object with the truncated filename.
Raises:
-
ValueError
–If the directory path is too long to accommodate any filename within the limit.
Example
truncate_filename('/path/to/example_long_filename.txt', 20) PosixPath('/path/to/example.txt')
Source code in bbot/core/helpers/misc.py
2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 |
|
url_depth
url_depth(url)
Calculate the depth of the given URL based on its path components.
Parameters:
-
url
(Union[str, ParseResult]
) –The URL whose depth is to be calculated.
Returns:
-
int
–The depth of the URL, based on its path components.
Examples:
>>> url_depth('https://www.evilcorp.com/foo/bar/')
2
>>> url_depth('https://www.evilcorp.com/foo//bar/baz/')
3
Source code in bbot/core/helpers/url.py
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
|
url_parents
url_parents(u)
Generate a list of parent URLs for a given URL string.
This function takes an input string u
representing a URL and generates a list of its parent URLs in decreasing order of specificity.
Parameters:
-
u
(str
) –The input string representing a URL.
Returns:
-
–
List[str]: A list of parent URLs of the input URL in decreasing order of specificity.
Examples:
>>> url_parents("http://www.evilcorp.co.uk/admin/tools/cmd.php")
["http://www.evilcorp.co.uk/admin/tools/", "http://www.evilcorp.co.uk/admin/", "http://www.evilcorp.co.uk/"]
Notes
- The list is generated by continuously calling
parent_url
until it returns None. - All components of the URL except for the path are preserved.
Source code in bbot/core/helpers/misc.py
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
|
verify_sudo_password
verify_sudo_password(sudo_pass)
Verify if the given sudo password is correct.
This function checks whether the sudo password provided is valid for the current user. It runs a command with sudo, feeding in the password via stdin, and checks the return code.
Parameters:
-
sudo_pass
(str
) –The sudo password to verify.
Returns:
-
bool
–True if the sudo password is correct, False otherwise.
Examples:
>>> verify_sudo_password("mysecretpassword")
True
Source code in bbot/core/helpers/misc.py
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 |
|
weighted_shuffle
weighted_shuffle(items, weights)
Shuffles a list of items based on their corresponding weights.
Parameters:
-
items
(list
) –The list of items to shuffle.
-
weights
(list
) –The list of weights corresponding to each item.
Returns:
-
list
–A new list containing the shuffled items.
Examples:
>>> items = ['apple', 'banana', 'cherry']
>>> weights = [0.4, 0.5, 0.1]
>>> weighted_shuffle(items, weights)
['banana', 'apple', 'cherry']
>>> weighted_shuffle(items, weights)
['apple', 'banana', 'cherry']
>>> weighted_shuffle(items, weights)
['apple', 'banana', 'cherry']
>>> weighted_shuffle(items, weights)
['banana', 'apple', 'cherry']
Note
The sum of all weights does not have to be 1. They will be normalized internally.
Source code in bbot/core/helpers/misc.py
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 |
|
which
which(*executables)
Finds the full path of the first available executable from a list of executables.
Parameters:
-
*executables
(str
, default:()
) –One or more executable names to search for.
Returns:
-
str
–The full path of the first available executable, or None if none are found.
Examples:
>>> which("python", "python3")
"/usr/bin/python"
Source code in bbot/core/helpers/misc.py
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 |
|