Добавить auto_cookies.py

Автоматическое создание профилей chrome и получение cookies файлов, с передачей на удалённый хост
This commit is contained in:
evgeniy_t 2025-02-08 12:15:51 +05:00
parent f76d950b33
commit 509c823884

178
auto_cookies.py Normal file
View File

@ -0,0 +1,178 @@
import os
import time
import subprocess
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
BASE_COOKIES_PATH = "/root/script/cookies" # Базовый путь для сохранения cookies
PRIVATE_KEY_PATH = "id_rsa" # Путь к приватному ключу для SCP
SERVER_USER = "root" # Пользователь на удалённом сервере
SERVER_IP = "45.140.146.245" # IP удалённого сервера
REMOTE_COOKIES_PATH = "/usr/script/cookies_" # Путь на удалённом сервере
BASE_CHROME_PROFILE_PATH = "/root/.chrome-profile_" # Базовый путь к профилю Chrome
# Акаунты
ACCOUNTS = [
{"email": "rugikmeg@gmail.com", "password": "k88mGHVQ"},
{"email": "13ivanill2025@gmail.com", "password": "k88mGHVQ"},
]
def is_profile_created(profile_index):
"""Проверка, создан ли профиль."""
profile_path = f"{BASE_CHROME_PROFILE_PATH}{profile_index}"
return os.path.exists(profile_path)
def is_logged_in(driver):
"""Проверка, выполнен ли вход в аккаунт YouTube."""
try:
driver.get("https://www.youtube.com")
time.sleep(3)
return "Sign in" not in driver.page_source
except Exception as e:
print(f"Ошибка при проверке авторизации: {e}")
return False
def login_to_youtube(driver, email, password):
"""Авторизация в YouTube."""
try:
driver.get("https://accounts.google.com/ServiceLogin?service=youtube&uilel=3&passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26app%3Ddesktop%26hl%3Den%26next%3D%252F&hl=en&ec=65620")
time.sleep(2)
# Вводим email
email_field = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "identifierId"))
)
email_field.send_keys(email)
email_field.send_keys(Keys.RETURN)
time.sleep(2)
# Вводим пароль
password_field = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.NAME, "Passwd"))
)
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN)
time.sleep(5)
# Проверяем успешность авторизации
return is_logged_in(driver)
except Exception as e:
print(f"Ошибка при авторизации: {e}")
return False
def extract_cookies(driver, profile_index):
"""Извлечение cookies и сохранение в файл."""
try:
cookies = driver.get_cookies()
cookies_path = f"{BASE_COOKIES_PATH}{profile_index}.txt"
with open(cookies_path, "w") as file:
file.write("# Netscape HTTP Cookie File\n")
file.write("# http://curl.haxx.se/rfc/cookie_spec.html\n")
file.write("# This is a generated file! Do not edit.\n\n")
for cookie in cookies:
expiry = cookie.get('expiry', '')
file.write(
f"{cookie['domain']}\tTRUE\t{cookie['path']}\t{str(cookie['secure']).upper()}\t{expiry}\t{cookie['name']}\t{cookie['value']}\n"
)
print(f"Cookies сохранены в {cookies_path}")
return True
except Exception as e:
print(f"Ошибка при извлечении cookies для профиля {profile_index}: {e}")
return False
def transfer_cookies_via_scp(profile_index):
"""Передача cookies на сервер через SCP."""
try:
if not os.path.exists(PRIVATE_KEY_PATH):
print(f" Файл ключа {PRIVATE_KEY_PATH} не найден.")
return False
# Команда SCP
cookies_path = f"{BASE_COOKIES_PATH}{profile_index}.txt"
remote_cookies_path = f"{REMOTE_COOKIES_PATH}{profile_index}.txt"
scp_command = [
"scp",
"-o", "StrictHostKeyChecking=no",
"-i", PRIVATE_KEY_PATH,
cookies_path,
f"{SERVER_USER}@{SERVER_IP}:{remote_cookies_path}"
]
# Выполняем SCP
result = subprocess.run(scp_command, check=True, text=True, capture_output=True)
if result.returncode == 0:
print(f"Cookies успешно переданы на сервер {SERVER_IP} для профиля {profile_index}.")
return True
else:
print(f"Ошибка при передаче cookies для профиля {profile_index}: {result.stderr}")
return False
except subprocess.CalledProcessError as e:
print(f"Ошибка при выполнении SCP для профиля {profile_index}: {e.stderr}")
return False
except Exception as e:
print(f"Общая ошибка для профиля {profile_index}: {e}")
return False
def process_profile(profile_index, email, password):
"""Обработка одного профиля."""
try:
# Настройки Chrome
options = Options()
# options.add_argument("--headless") # Без интерфейса
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
# Указываем профиль пользователя
profile_path = f"{BASE_CHROME_PROFILE_PATH}{profile_index}"
options.add_argument(f"--user-data-dir={profile_path}")
options.add_argument("--profile-directory=Default")
# Запуск браузера
driver = webdriver.Chrome(options=options)
# Проверка авторизации
if is_profile_created(profile_index):
print(f"Профиль {profile_index} уже создан. Проверяем авторизацию...")
if not is_logged_in(driver):
print(f"Пользователь не авторизован. Пытаемся войти...")
if not login_to_youtube(driver, email, password):
print(f" Не удалось авторизоваться для профиля {profile_index}.")
driver.quit()
return False
else:
print(f"Профиль {profile_index} не создан. Создаем и авторизуемся...")
if not login_to_youtube(driver, email, password):
print(f" Не удалось авторизоваться для профиля {profile_index}.")
driver.quit()
return False
# Извлекаем куки
if extract_cookies(driver, profile_index):
if transfer_cookies_via_scp(profile_index):
print(f" Процесс завершён успешно для профиля {profile_index}.")
else:
print(f"Ошибка при передаче cookies для профиля {profile_index}.")
else:
print(f"Ошибка при извлечении cookies для профиля {profile_index}.")
driver.quit()
return True
except Exception as e:
print(f"Общая ошибка выполнения скрипта для профиля {profile_index}: {e}")
return False
if __name__ == "__main__":
print("Начинаем выполнение скрипта.")
for profile_index, account in enumerate(ACCOUNTS, start=1):
print(f"Обработка профиля {profile_index}...")
process_profile(profile_index, account["email"], account["password"])
print("Все профили обработаны.")