yt-dlp_e/auto_cookies.py
evgeniy_t 3fee94cb1b Обновить auto_cookies.py
Добавление параметра прокси в настройки Chrome, добавлена переменная ENABLE_LOGIN для отключения функции логина в акаунты, добавление переменной для указания количества создаваемых профилей Chrome
2025-02-10 01:38:08 +05:00

195 lines
9.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
# Включение/отключение функции логина
ENABLE_LOGIN = False # Если False, скрипт просто создаст профиль и откроет YouTube
# Количество создаваемых профилей
NUM_PROFILES = 5 # Сколько профилей Chrome создать
# Аккаунты
ACCOUNTS = [
{"email": "rugikmeg@gmail.com", "password": "k88mGHVQ", "proxy": "socks5://127.0.0.1:1080"},
{"email": "13ivanill2025@gmail.com", "password": "k88mGHVQ", "proxy": "socks5://127.0.0.1:1081"},
]
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, proxy):
"""Обработка одного профиля."""
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")
# Добавляем прокси
if proxy:
options.add_argument(f"--proxy-server={proxy}")
# Запуск браузера
driver = webdriver.Chrome(options=options)
if ENABLE_LOGIN:
# Проверка авторизации
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}.")
else:
# Если логин отключен, просто открываем YouTube
print(f"Логин отключен. Профиль {profile_index} создан, открываем YouTube...")
driver.get("https://www.youtube.com")
time.sleep(5) # Даем время для загрузки страницы
driver.quit()
return True
except Exception as e:
print(f"Общая ошибка выполнения скрипта для профиля {profile_index}: {e}")
return False
if __name__ == "__main__":
print("Начинаем выполнение скрипта.")
for profile_index in range(1, NUM_PROFILES + 1):
# Выбираем аккаунт по кругу, если количество профилей больше, чем аккаунтов
account = ACCOUNTS[(profile_index - 1) % len(ACCOUNTS)]
print(f"Обработка профиля {profile_index}...")
process_profile(profile_index, account["email"], account["password"], account.get("proxy"))
print("Все профили обработаны.")