get_web_session.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. #!/usr/bin/env python3
  2. """
  3. Authenticates with X.com/Twitter and extracts session cookies for use with Nitter.
  4. Handles 2FA, extracts user info, and outputs clean JSON for sessions.jsonl.
  5. Requirements:
  6. pip install -r tools/requirements.txt
  7. Usage:
  8. python3 tools/get_web_session.py <username> <password> [totp_seed] [--append sessions.jsonl] [--headless]
  9. Examples:
  10. # Output to terminal
  11. python3 tools/get_web_session.py myusername mypassword TOTP_BASE32_SECRET
  12. # Append to sessions.jsonl
  13. python3 tools/get_web_session.py myusername mypassword TOTP_SECRET --append sessions.jsonl
  14. # Headless mode (may increase detection risk)
  15. python3 tools/get_web_session.py myusername mypassword TOTP_SECRET --headless
  16. Output:
  17. {"kind": "cookie", "username": "...", "id": "...", "auth_token": "...", "ct0": "..."}
  18. """
  19. import sys
  20. import json
  21. import asyncio
  22. import pyotp
  23. import nodriver as uc
  24. async def login_and_get_cookies(username, password, totp_seed=None, headless=False):
  25. """Authenticate with X.com and extract session cookies"""
  26. # Note: headless mode may increase detection risk from bot-detection systems
  27. browser = await uc.start(headless=headless)
  28. tab = await browser.get('https://x.com/i/flow/login')
  29. try:
  30. # Enter username
  31. print('[*] Entering username...', file=sys.stderr)
  32. username_input = await tab.find('input[autocomplete="username"]', timeout=10)
  33. await username_input.send_keys(username + '\n')
  34. await asyncio.sleep(1)
  35. # Enter password
  36. print('[*] Entering password...', file=sys.stderr)
  37. password_input = await tab.find('input[autocomplete="current-password"]', timeout=15)
  38. await password_input.send_keys(password + '\n')
  39. await asyncio.sleep(2)
  40. # Handle 2FA if needed
  41. page_content = await tab.get_content()
  42. if 'verification code' in page_content or 'Enter code' in page_content:
  43. if not totp_seed:
  44. raise Exception('2FA required but no TOTP seed provided')
  45. print('[*] 2FA detected, entering code...', file=sys.stderr)
  46. totp_code = pyotp.TOTP(totp_seed).now()
  47. code_input = await tab.select('input[type="text"]')
  48. await code_input.send_keys(totp_code + '\n')
  49. await asyncio.sleep(3)
  50. # Get cookies
  51. print('[*] Retrieving cookies...', file=sys.stderr)
  52. for _ in range(20): # 20 second timeout
  53. cookies = await browser.cookies.get_all()
  54. cookies_dict = {cookie.name: cookie.value for cookie in cookies}
  55. if 'auth_token' in cookies_dict and 'ct0' in cookies_dict:
  56. print('[*] Found both cookies', file=sys.stderr)
  57. # Extract ID from twid cookie (may be URL-encoded)
  58. user_id = None
  59. if 'twid' in cookies_dict:
  60. twid = cookies_dict['twid']
  61. # Try to extract the ID from twid (format: u%3D<id> or u=<id>)
  62. if 'u%3D' in twid:
  63. user_id = twid.split('u%3D')[1].split('&')[0]
  64. elif 'u=' in twid:
  65. user_id = twid.split('u=')[1].split('&')[0]
  66. cookies_dict['username'] = username
  67. if user_id:
  68. cookies_dict['id'] = user_id
  69. return cookies_dict
  70. await asyncio.sleep(1)
  71. raise Exception('Timeout waiting for cookies')
  72. finally:
  73. browser.stop()
  74. async def main():
  75. if len(sys.argv) < 3:
  76. print('Usage: python3 twitter-auth.py username password [totp_seed] [--append sessions.jsonl] [--headless]')
  77. sys.exit(1)
  78. username = sys.argv[1]
  79. password = sys.argv[2]
  80. totp_seed = None
  81. append_file = None
  82. headless = False
  83. # Parse optional arguments
  84. for i, arg in enumerate(sys.argv[3:], 3):
  85. if arg == '--append' and i + 1 < len(sys.argv):
  86. append_file = sys.argv[i + 1]
  87. elif arg == '--headless':
  88. headless = True
  89. elif not arg.startswith('--'):
  90. totp_seed = arg
  91. try:
  92. cookies = await login_and_get_cookies(username, password, totp_seed, headless)
  93. session = {
  94. 'kind': 'cookie',
  95. 'username': cookies['username'],
  96. 'id': cookies.get('id'),
  97. 'auth_token': cookies['auth_token'],
  98. 'ct0': cookies['ct0']
  99. }
  100. output = json.dumps(session)
  101. if append_file:
  102. with open(append_file, 'a') as f:
  103. f.write(output + '\n')
  104. print(f'✓ Session appended to {append_file}', file=sys.stderr)
  105. else:
  106. print(output)
  107. os._exit(0)
  108. except Exception as error:
  109. print(f'[!] Error: {error}', file=sys.stderr)
  110. sys.exit(1)
  111. if __name__ == '__main__':
  112. asyncio.run(main())