introduction
In the era of mobile Internet, SMS verification codes have become an important security means in the process of identity verification, account registration, login protection, etc. However, manually entering verification codes is not only inefficient, but also prone to errors. This article will introduce how to use Python to build a SMS forwarder to realize the automatic reception, identification and forwarding of verification codes, making your work and life more convenient.
1. Preparation
1.1 Hardware and software requirements
Hardware: Android phone (developer mode needs to be turned on), computer
software:
- Python environment (Python 3.6+ recommended)
- ADB Tools (Android Debug Bridge)
- SMS processing library (such as py-android-sms)
- Web frameworks (such as Flask)
- Verification code identification library (such as ddddocr)
1.2 Environment configuration
Install ADB Tools
ADB is part of the Android Developer Toolkit and can be installed in the following ways:
Windows: From/studio/releases/platform-tools
Mac/Linux: Install through terminal commands:
# Mac brew install android-platform-tools # Ubuntu sudo apt install android-tools-adb
After the installation is completed, run adb version to verify that the installation is successful.
- Enable mobile phone developer mode
- Turn on the phone "Settings".
- Enter "About Mobile" and click "version number" 7 times in a row until the prompt "Developer mode is enabled".
- Return to settings, go to "Developer Options", and turn on "USB Debugging".
- Connect your phone to your computer
- Connect the phone to the computer via USB cable and run adb devices. If the device ID is displayed, it means the connection is successful.
Install Python dependency library
pip install adb-shell flask ddddocr
2. Core function implementation
2.1 SMS monitoring and acquisition
Use ADB tools to monitor mobile phone text messages and extract text message content and sender information.
import subprocess import re def get_sms(): try: # Execute ADB command to get text messages result = ( ["adb", "shell", "content", "query", "--uri", "content://sms/inbox", "--projection", "address,body,date"], capture_output=True, text=True ) return except Exception as e: print(f"Failed to get text messages: {e}") return None def parse_sms(sms_data): messages = sms_data.split("\n") for message in messages: if "body=" in message: # Extract text message content body_start = ("body=") + len("body=") body_end = (",", body_start) body = message[body_start:body_end] # Extract sender number address_start = ("address=") + len("address=") address_end = (",", address_start) address = message[address_start:address_end] yield address, body # Example: Get and parse SMSsms_data = get_sms() if sms_data: for address, body in parse_sms(sms_data): print(f"Sender: {address}, content: {body}")
2.2 Verification code identification
Use regular expressions or ddddocr library to identify verification codes in SMS.
Method 1: Regular Expression
def extract_verification_code(sms_body): # Assume that the verification code is 6 digits code = (r'\b\d{6}\b', sms_body) return (0) if code else None
Method 2: ddddocr library
import ddddocr def ocr_verification_code(image_path): ocr = () with open(image_path, 'rb') as f: image = () return (image)
2.3 Data Forwarding
The identified verification code is forwarded to the specified receiver (such as web applications, API interfaces, etc.) through HTTP requests or WebSocket.
from flask import Flask, request app = Flask(__name__) @('/forward', methods=['POST']) def forward(): data = code = ('code') # Forward verification code to the target address # For example: (url, json={'code': code}) return {'status': 'success', 'message': f'Verification code [code] forwarded'} if __name__ == '__main__': (port=5000)
3. Advanced function expansion
3.1 Multi-device support
Extend the program to support multiple Android devices to work simultaneously through multi-threading or asynchronous programming.
import threading def monitor_device(device_id): while True: sms_data = get_sms(device_id) if sms_data: for address, body in parse_sms(sms_data): code = extract_verification_code(body) if code: forward(code) # Start multiple device monitoring threadsdevices = ['device1', 'device2', 'device3'] for device in devices: thread = (target=monitor_device, args=(device,)) ()
3.2 Security enhancement
- Authentication: Add token authentication to the forwarding interface to prevent unauthorized access.
- Data encryption: Use HTTPS protocol to transmit data to ensure communication security.
3.3 Performance optimization
- Caching mechanism: cache processed SMS IDs to avoid duplicate processing.
- Asynchronous processing: Use asynchronous frameworks (such as FastAPI) to improve concurrent processing capabilities.
4. Practical cases: Build a complete SMS forwarding system
4.1 System Architecture
Mobile phone (SMS reception) -> ADB tool (SMS monitoring) -> Python script (analysis and recognition) -> Web interface (data forwarding) -> Target application
4.2 Complete code example
import subprocess import re from flask import Flask, request import threading app = Flask(__name__) def get_sms(device_id=None): # Obtain SMS based on device ID (multi-device support) command = ["adb", "shell", "content", "query", "--uri", "content://sms/inbox", "--projection", "address,body,date"] if device_id: (1, f"-s {device_id}") result = (command, capture_output=True, text=True) return def parse_sms(sms_data): messages = sms_data.split("\n") for message in messages: if "body=" in message: body_start = ("body=") + len("body=") body_end = (",", body_start) body = message[body_start:body_end] address_start = ("address=") + len("address=") address_end = (",", address_start) address = message[address_start:address_end] yield address, body def extract_verification_code(sms_body): code = (r'\b\d{6}\b', sms_body) return (0) if code else None @('/forward', methods=['POST']) def forward(): data = code = ('code') # Implement forwarding logic print(f"Verification Code [code] forwarded") return {'status': 'success'} def monitor_device(device_id): while True: sms_data = get_sms(device_id) if sms_data: for address, body in parse_sms(sms_data): code = extract_verification_code(body) if code: # Call the forwarding interface ['DEBUG'] = False ['TESTING'] = False with app.app_context(): forward_result = forward(json={'code': code}) print(forward_result) if __name__ == '__main__': # Start multiple device monitoring threads devices = ['device1', 'device2'] # Replace with the actual device ID for device in devices: thread = (target=monitor_device, args=(device,)) () (port=5000)
4.3 Run and test
- Save the code as sms_forwarder.py.
- Connect to Android devices to make sure ADB is recognizable.
- Run the script: python sms_forwarder.py.
- Send test text messages to your phone and observe the console output and forwarding results.
5. Summary and Outlook
This article introduces how to use Python to build a SMS forwarder to realize the automatic reception, identification and forwarding of verification codes. By combining ADB tools, SMS processing library and Web framework, we have built an efficient and stable system. In the future, functions can be further expanded, such as supporting more types of verification code recognition, adding graphical interfaces, and implementing cloud deployment, making SMS forwarders smarter and easier to use.
This is the article about Python’s automated reception and processing of mobile phone verification codes. For more related Python verification code content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!