-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Added phone number generator and normaliser script file #11
Conversation
PS Не уверен, что скажет куратор насчет собственноручной имплементации. Возможно, где-то в интернете есть api, делающее все то же самое, но при этом правильно. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Прикольные мутации, посмотреть интересно. Есть несколько моментов:
- Нужно поправить комментарии и написать их на английском (я это отметил)
- Нужно добавить аннотацию типов (https://docs.python.org/3/library/typing.html, можно погуглить или воспользоваться моими комментариями)
- Нужно посмотреть насчет 8- / +7-, т.е. это справедливо только для РФ. В целом - ок, для нас ок, но в глобальном контексте надо будет ещё посмотреть, как это можно поправить. Может, поискать доступный web API сервис, который может это делать?
Есть ещё просьба:
- Перенеси, пожалуйста, папку
/phone_num_generator/
в папку/src/scripts/convert/
, т.е. вместо osint -> convert, т.к. это не совсем осинт кейс, а скорее что-то более общее. - Переименуй, пожалуйста, скрипт
script.py
в__main__.py
Я добавлю класс для конвертеров, от которого можно наследоваться. Пока можно сделать базовый класс Runner
как в других скриптах, просто не наследовать ни от чего (потом наследуемся, когда поправим это ревью и я допишу внешний класс).
А так хорошая работа, спасибо! Буду ждать указанных изменений и сделаем новую ревьюшку.
@@ -0,0 +1,54 @@ | |||
#!/usr/bin/env python3 | |||
|
|||
import random |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если не ошибаюсь, то в скрипте из random
используется только randint
. В этом случае можно только randint
и импортировать:
from random import randint
Или:
from random import randint as random_number
random_number(1, 9)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed
def rand_num_gen(): | ||
# генерирует случайный номер для теста | ||
# args: none | ||
# return: 11-digit number |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Когда пишем код, докстринги обязательно на английском! По формату докстрингов лучше придерживаться чего-то типа:
def rand_num_gen() -> str:
"""
Generates random numbers for the test
:return: string representation of the number
"""
Если аргументов нет, их можно не вносить в доки. И лучше добавлять аннотацию типов :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed
# генерирует случайный номер для теста | ||
# args: none | ||
# return: 11-digit number | ||
ans = '8' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
К сожалению, данная логика будет работать только для +7-... или 8-... номеров, т.е. для России. В контексте ru номеров - ок, но в общем случае тяжеловато.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В принципе, для нас, для начала (как стартовая точка отсчета) - норм. В дальнейшем надо будет подумать как ставить код, или может использовать API какой-нибудь.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можно попробовать погуглить, есть ли какие-нибудь онлайн сервисы генерации разных форматов.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed for now, might need a second review
# args: none | ||
# return: 11-digit number | ||
ans = '8' | ||
for i in range(1, 11): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можно немного проще:
for _ in range(10)
Т.к. i ты не используешь здесь, а просто генерируешь случайно.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed
for i in range(1, 11): | ||
ans += str(random.randint(1, 9)) | ||
return ans |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можно сделать так:
return "8" + "".join([str(random.randint(1, 9)) for _ in range(10)])
Попробуй разобраться в этой строке. Если не поймешь, посмотрим вместе. Тут python list comprehension, можешь погуглить.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
поняла и исправила, так что тоже fixed :)
numbers = [digit for digit in phone_num if digit.isdigit()] | ||
norm_num = "".join(numbers) | ||
if len(norm_num) == 11: | ||
norm_num = '7' + norm_num |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Смотри :)
778269923566
Это результат работы нормалайзера. Если мы говорим про ru номера, то у нас 11 знаков, а тут, получается, если у нас уже есть 11 знаков, мы добавляем 7.
Т.е., если разобрать, то выходит что-то типа:
7-8-913-881-11-11
Немножко неправильно :)
# генерирует все возможные варианты написания | ||
# args: нормализированный номер | ||
# return: список строк номеров | ||
number_groups = [norm_num[0], norm_num[1:4], norm_num[4:7], norm_num[7:9], norm_num[9:11]] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok 👌
Можно ещё сделать так, чтобы не дублировать norm_num
:
number_groups = [norm_num[first: second] for first, second in [(0, 1), (1, 4), (4, 7), (7, 9), (9, 11)]]
for sep in separators: # автоматизированный процесс для некоторых | ||
num_list.append(sep.join(number_groups)) | ||
num_list.append("+" + sep.join(number_groups)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Как пример:
joined = sep.join(number_groups)
num_list.extend((joined, f"+{joined}"))
Один раз собираем цифры, один раз делаем добавление в лист - вместо 2 джойнов 1, вместо 2 аппендов 1 экстенд)
number_groups = [norm_num[0], norm_num[1:4], norm_num[4:7], norm_num[7:9], norm_num[9:11]] | ||
num_list = [] | ||
separators = ["", "-", "."] | ||
for sep in separators: # автоматизированный процесс для некоторых |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
И коммент лучше ставить над кодом, и на английском
# Automate some separations of numbers, etc...
for sep ...
num_list.append( | ||
number_groups[0] + "(" + number_groups[1] + ")" + number_groups[2] + number_groups[3] + number_groups[4]) | ||
num_list.append( | ||
"+" + number_groups[0] + "(" + number_groups[1] + ")" + number_groups[2] + number_groups[3] + number_groups[4]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можно сделать вот так до цикла for sep in separators:
phone_w_brackets = "{prefix}({code}){rest}".format(
prefix=number_groups[0],
code=number_groups[1],
rest="".join(number_groups[2:])
)
num_list.extend((phone_w_brackets, f"+{phone_w_brackets}"))
Можно попробовать найти лист кодов стран в txt и генерить на их базе, что-нибудь типа такого: https://countrycode.org/ но в виде .txt кодов |
Вот, кстати! Вроде неплохой пример: ⭐ Обрати внимание сюда ещё: Здесь же можно сразу забирать необходимые форматы, посмотри в документацию:
|
…-team/osint-framework into phone_number_generator
775b00b
to
ef85dbb
Compare
@marinepalyan По коду - уже не хватает глаз посмотреть свежим взглядом, поэтому, наверное, завтра догляжу конкретно. Пока что поверхностно хочу отметить, что есть небольшой баг (или, может, я что-то не понимаю): при подаче номера "+79138811111" всё отрабатывает ок, но при подаче "89138811111" - уже ничего не работает. Может, это не международный формат? И ещё небольшое замечание по выдаче:
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ок 👍
Тестов можно было побольше добавить, но в принципе основное всё на месте, можно сказать, smoke-test.
Если что-то увижу, кину issue или пофикшу.
Спасибо! Хорошая работа :)
* WIP: Add Initial Version (alpha-beta-gamma) (#1) * Add initial WIP project version * Update src code * Update documentation * Add requirements * add script name_check (#4) * Add initial WIP project version * add check_nickname.py, check_nickname_sync and check_nickname_async in it add social_networks.txt * add check_nickname.py, check_nickname_sync and check_nickname_async in it add social_networks.txt * new main.py * new base: develop add many files * fix inheritance in Runner * fix check_nickname fix social_networks.txt * Little fixes * Return default main value Co-authored-by: manmolecular <regwebghost@yandex.ru> * Add script: region check (#5) * Added number to Possiblekeys in osint.py. Added number as kwarg in main.py. Script defines the region where the phone number is registrated * Changed number->phone * Little fixes, update requirements Co-authored-by: manmolecular <regwebghost@yandex.ru> * add script (email_verifier) (#7) * add script (email_verifier) * add library * change req and so on * used black * Little fixes * Main and .gitignore fixes Co-authored-by: Minerm <minerm@mail.ru> Co-authored-by: manmolecular <regwebghost@yandex.ru> * Add script to get allowed http methods. (#10) * Add script to get allowed http methods. * 'Handle' more probable exceptions * Changed name of script directory * Remove wildcard import * Add random method check. Alter script response. * Little fixes * Fix methods variable * Fix typo in requirements Co-authored-by: manmolecular <regwebghost@yandex.ru> * Add script to calculate hash of favicon.ico for Shodan (#13) * Add script to calculate hash of favicon.ico * Remove '\n' * Change variable name * Core fixes. Provide global variables. Update runner. Upgrade module-package system. (#14) * Clean init all the modules with the __init__.py file * Remove unused gitkeeps * Add base inits for script packages * Update main file * Set __file__ variable at the module level * Add inits for the modules * Modify all the modules * Delete one more .gitkeep * Add WIP test for user_greeting * Update test module for user_greeting * Fix module runner a bit * Add relative imports to the modules * Add run tests script * Update README.md * Fix module-package runner * Update requirements * Format everything with Black * Handle module and execution errors with runner * Awesome cookie checker (#6) * made cookie checker task * added requirements.txt * refactored the code & adapted to the new project structure * small fix that processes exception * Little fixes Co-authored-by: manmolecular <regwebghost@yandex.ru> * Added a function for retrieving location and provider info by IP address. (#12) * Added IP address as one of the possible keys. * Init commit. * Init commit. * Added dosctring. * Removed some emptry lines. * get_ip_info was moved into Runner class. * The IP key shouldn't be here. * Reworked exception handling mechanism. * Codestyle fix. * Removed some test code. * Moved script to proper dir. * Fixed response returned in case of error. * Fixed exception handling. * Request now uses the validated IP. * Found a better variable name for validated IP. * Removed unnecessary variables. * Init commit. * Runner class was moved into this module. * Set default IP to Google DNS Resolver address (to be more stable) * Add default values; set default ip to 8.8.8.8; set default city to Ashburn * Apply Black linter on the main module file Co-authored-by: manmolecular <regwebghost@yandex.ru> * Add simple server mocking test example (#20) * Add simple web server mocking example * Add some types * Add tests for favicon hash (#22) * Add tests for favicon hash * Apply Black linting * Suppress server output logging Co-authored-by: manmolecular <regwebghost@yandex.ru> * Test allowed_methods. Modify allowed_methods. (#21) * * Make allowed_methods also return methods on which server did not response. * Add tests for allowed_methods module. * Fix output * Change docstring * Linting with Black Co-authored-by: manmolecular <regwebghost@yandex.ru> * Fix tests timeouts (#25) * Add tests defaults (#26) * Boost up/improvement: Add multiprocessing CaseManager (processes, threads, parallel case execution) (#27) * Add multiprocessing CaseManager * Add more info about case to the manager * Update logging format * Set optimal threads and processes quantity * simple email generator (#9) * Made simple email generator, modified requirements.txt * deleted __main__ rubbish, modified success message * added a check on username availability * Update __main__.py * Update __main__.py * modified names of methods and atributes * Update requirements.txt * reduced number of domen names, possible emails; reduced reversing and optimized code; moved project to convert/ dir; led project to a new view * fixed bug with command prompt; got rid of json; moved service symbols to a separate class; optimized code; made cosmetic changes * some fixes * some fixes * Add fixes Co-authored-by: manmolecular <regwebghost@yandex.ru> * Added phone number generator and normaliser script file (#11) * Added phone number generator and normaliser script file * Added feature directory and empty files * Added module.py * Added Runner class to main.py * Cleaned up the comments and reformatted code * Added library to the main requirements.txt * Changed module.py * Changed module.py * Deleted old script file * Fixed requirements bug * Add phone_num_generator module * Corrected double brackets and dot format mistakes * Something went wrong last time, so no2 * Added unittests and local number format * Fix main module runner * Remove code duplicate Co-authored-by: manmolecular <regwebghost@yandex.ru> * Get title (#23) * add main code * add __init__.py,__main__.py,module.py,test_module.py * fix module.py fix test_module.py * add test_module.py * add requirements.txt * fix tests,module.py add new lines in __main__.py and __init__.py * Remove old format string * Delete test_module from check_nickname * Module fixes Co-authored-by: manmolecular <regwebghost@yandex.ru> * Suppress Requests keep-alive socket warnings (#33) * Iknowwhatyoudownload (#24) * added torrent module * underscores bugfix * added docstrings * updated requirements * changed directory * Added required changes * Fix base runners * Remove API key, fix main runner * Linting with Black Co-authored-by: omarkelov <36790281+omarkelov@users.noreply.github.com> Co-authored-by: Anton Nikolaev <regwebghost@yandex.ru> * add test_module.py in email_verifier (#29) * add test_module.py * Add functions (test_pass_false / true_arguments) * Fix comparison * Fix return types Co-authored-by: Minerm <minerm@mail.ru> Co-authored-by: manmolecular <regwebghost@yandex.ru> * Fix validator keys (#35) * Develop: fixes, improvements, etc. (#36) * Suppress insecure request warning messages * Update requirements.txt * Add base scenario, add yaml support * Update structure; include results saving * Improvements - skip not applicable scripts, fix workers system (#39) * Fix executors * Optimize imports * Add results to gitignore * Add 'required' field to define required args * Ignore results from 'results' directory * Add 'required' field to base classes * Skip not applicable scripts * Fix quantity of processes * Set the execution timeout to 5 mins per case * Add phone case to the examples * JSON Russian language and encoding support * Add core default values * Remove hardcoded quantity of workers * Increase quantity of cases up to 10 * Fix indentation in runner * Add seed (initial) data to scan for * Email generator fix and tests (#38) * added tests * fixed incorrect behavior * extension of tests, cosmetic changes * Add google_search module (#37) * Add module scraping search results. * Add tests to google_search script * Add tests and do minor refactoring * Add input type test * Apply black linting * Add request delay when needed * Remove redundant import * Fixes (#40) * Add 'required' field for the google search module * Add beatifulsoup to requirements * Check nickname (#28) * add main code * add __init__.py,__main__.py,module.py,test_module.py * fix module.py fix test_module.py * add test_module.py * add requirements.txt * fix tests,module.py add new lines in __main__.py and __init__.py * add test_module.py * delete get_title * add some tests to test_module.py fix social_networks.txt * fix styles modify social_networks.txt * fix module.py fix test_module.py * Cosmetic fixes Co-authored-by: manmolecular <regwebghost@yandex.ru> * Update README.md * Add Tornado-based web-server. Support REST API methods. Implement task manager. (#41) * Modify environment files * Move saver to another module * Add SQLite database handling * Add Tornado server * Add main server runner * Move saver to another module * Add multiprocessing * Add docker-compose and postgres * Update database handling * Update environment files * Remove unused imports from main.py * Update database handlers * Update task manager; handle task status * Fix task spawner * Little cosmetic fixes, format files * Format with Black * Add environment variables * Add limit parameter to the task list handler * Don't initialize task spawner, it's not required * Remove single case wrapper from the main.py * Add Docker support for server * Fix makefile: spaces to tabs * Format with Black * Cosmetic: add new line to dockerignore * Add healthcheckers * Add CLI interface * Add color logging * Update gitignore * Add parents for scripts in logging * Fix makefile * Add screenshots * Update README.md * Update README.md Co-authored-by: Iandmee <48530455+Iandmee@users.noreply.github.com> Co-authored-by: sph-668 <68100447+sph-668@users.noreply.github.com> Co-authored-by: Neo <55306931+Shas08@users.noreply.github.com> Co-authored-by: Minerm <minerm@mail.ru> Co-authored-by: Nikita Kryukov <cravtos92@gmail.com> Co-authored-by: HochuOlivie <49933393+HochuOlivie@users.noreply.github.com> Co-authored-by: Timur <36272321+SN4KEBYTE@users.noreply.github.com> Co-authored-by: Matvey Sergeev <47077074+Enhisir@users.noreply.github.com> Co-authored-by: marinepalyan <50265835+marinepalyan@users.noreply.github.com> Co-authored-by: katerina <42969775+edubinskaya18214@users.noreply.github.com> Co-authored-by: omarkelov <36790281+omarkelov@users.noreply.github.com>
For now I only added the main logic of the script. I don't fully understand how to use the framework in this case, since I'm not sending any requests to websites. This is just for format. So I'm waiting for your comments.
Also, I think the "test" function should be removed, idk.