Skip to content

Instantly share code, notes, and snippets.

@Touexe
Last active February 24, 2022 03:11
Show Gist options
  • Save Touexe/9d067d8dc197b021b9c50be5ca6eef8d to your computer and use it in GitHub Desktop.
Save Touexe/9d067d8dc197b021b9c50be5ca6eef8d to your computer and use it in GitHub Desktop.
Get all recovery addresses from Microsoft account
from typing import Any, Optional
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from bs4 import BeautifulSoup
import re
import shutil
import time
from platform import system, uname
class Os:
def __init__(self):
syst = system().lower()
self.wsl = False
self.mac = False
self.linux = False
self.windows = False
if 'darwin' in syst:
self.mac = True
self.os = 'mac'
elif 'linux' in syst:
self.linux = True
self.os = 'linux'
if 'Microsoft' in uname().release:
self.wsl = True
self.linux = False
self.os = 'wsl'
elif 'windows' in syst:
self.windows = True
self.os = 'windows'
def __str__(self):
return self.os
def get_driverpath():
driver_path = shutil.which("chromedriver")
if driver_path:
return driver_path
chromedrivermanager_silent = ChromeDriverManager(print_first_line=False, log_level=0)
driver = chromedrivermanager_silent.driver
driverpath_with_version = chromedrivermanager_silent.driver_cache.find_driver(driver.browser_version, driver.get_name(), driver.get_os_type(), driver.get_version())
driverpath_without_version = chromedrivermanager_silent.driver_cache.find_driver("", driver.get_name(), driver.get_os_type(), "")
if driverpath_with_version:
return driverpath_with_version
elif not driverpath_with_version and driverpath_without_version:
print("[Webdrivers Manager] Updating the chromedriver...")
driver_path = ChromeDriverManager().install()
print("[Webdrivers Manager] The chromedriver has been updated !\n")
else:
print("[Webdrivers Manager] The chromedriver was not. Downloading and installing...")
driver_path = ChromeDriverManager().install()
print("[Webdrivers Manager] The chromedriver has been installed !\n")
return driver_path
def get_chrome_options_args(is_headless):
chrome_options = Options()
chrome_options.add_argument('--log-level=3')
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
# chrome_options.add_experimental_option("debuggerAddress","localhost:9222")
chrome_options.add_argument("--no-sandbox")
if is_headless:
chrome_options.add_argument("--headless")
if (Os().wsl or Os().windows) and is_headless:
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-setuid-sandbox")
chrome_options.add_argument("--no-first-run")
chrome_options.add_argument("--no-zygote")
chrome_options.add_argument("--single-process")
chrome_options.add_argument("--disable-features=VizDisplayCompositor")
return chrome_options
class Microsoft:
def __init__(self):
self.elements = {"credentialbox": {"locator": By.XPATH, "value":"//input[@type='email']"},
"is_sign_in_phone": {"locator": By.ID, "value":"isSigninNamePhone"},
"submit" : {"locator": By.XPATH, "value": "//input[@type='submit']"},
"forgotpsw": (By.LINK_TEXT, "Forgot password?"),
"show_more_methods": (By.LINK_TEXT, "Show more verification methods"),
"use_different_verification_option": (By.LINK_TEXT, "Use a different verification option"),
"other_way_to_sign_in": (By.LINK_TEXT, "Other ways to sign in")
}
def initiate(self, is_headless : bool = True) -> bool:
self.chrome_options = get_chrome_options_args(is_headless)
if is_headless:
print(f"[Chrome] Chrome is running in headless mode")
self.chrome_driver_path = Service(get_driverpath())
self.driver = Chrome(service = self.chrome_driver_path, options = self.chrome_options)
return True
def wait_for(self, locator : Any, timeout : int = 5) -> Any:
try:
element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator))
return element
except TimeoutException:
return None
def enter_credential(self, credential: str):
url = "https://account.live.com/password/reset"
print(f"[Chrome] Navigating to {url}")
self.driver.get(url)
print(f"[Chrome] Entered credential : {credential}")
credential_box = self.wait_for(self.elements["credentialbox"].values())
credential_box.send_keys(credential)
credential_box.send_keys(Keys.ENTER)
time.sleep(0.5)
try:
is_sign_in_phone : str = self.wait_for(self.elements["is_sign_in_phone"].values(), timeout = 1 ).get_attribute("value")
if is_sign_in_phone == "True":
print("passed?")
self.driver.find_element(By.XPATH, "//option[@value='KH']").click()
self.driver.find_element(self.elements["submit"]["locator"], self.elements["submit"]["value"]).click()
except (NoSuchElementException, AttributeError):
pass
invalid_account_element = self.wait_for((By.ID, "pMemberNameErr"), timeout = 1)
if invalid_account_element:
if invalid_account_element.text == "Try entering your Microsoft account again. We don't recognize this one.":
print(f"[Chrome] Invalid credential")
return False
return True
def show_more_verification_method(self):
for element in (self.elements["show_more_methods"], self.elements["use_different_verification_option"]):
show_more = self.wait_for(locator = element, timeout = 0.5)
if show_more:
break
show_more.click()
def get_recovering_credentials(self):
page_source = BeautifulSoup(self.driver.page_source, 'lxml')
credential_elements = page_source.find_all("div", class_="radio")
all_credentials = []
for credential_element in credential_elements:
raw_credential = credential_element.get_text().strip()
if raw_credential == "Use an authenticator app":
continue
cleaned_credential = re.sub("Email |Text ", "", raw_credential)
all_credentials.append(cleaned_credential)
print(f"[Chrome] Found {len(all_credentials)} credentials")
print(f"[Chrome] Credentials : {' | '.join(all_credentials)}")
return all_credentials
def run(self, credential: str):
self.initiate()
if not self.enter_credential(credential):
return []
self.show_more_verification_method()
return self.get_recovering_credentials()
def main():
microsoft = Microsoft()
# creds = microsoft.run("example@gmail.com") # Email test
# creds = microsoft.run("89XXXXXX") # Phone number test
creds = microsoft.run("example.studios") # skye name test
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment