目录
Android的短信存储在content provider中,通常是content://sms/inbox。可根据短信的内容、发件人号码或时间戳来筛选短息。因此,ADB命令需要包含这些条件。例如,使用--where参数来指定条件,比如address='号码'或body LIKE '%关键词%'。
短信数据库路径,不同设备短信URI可能不同(通过调整--uri
参数可操作不同短信箱),常见的有:
-
content://sms/inbox
(收件箱) -
content://sms/sent
(已发送) -
content://sms/draft
(草稿箱) -
content://sms/all (所有短信)
-
content://sms/outbox 发件箱(尚未发送)
-
content://sms/failed 发送失败的短信
读取短息
定位目标短信的_id
:短信数据库中的每条记录都有唯一的_id
字段。可以通过获取它进行其他操作。
query_cmd = [
"adb", "shell",
"content", "query", "--uri", "content://sms/inbox",
"--projection", "_id",
"--where", f"address='{sender}'" # sender表示发件人的号码
]
result = subprocess.run(query_cmd, capture_output=True, text=True)
按发件人号码和内容筛选
adb shell content query --uri content://sms/inbox \
--projection _id,address,body,date \
--where "address='1234567890' AND body LIKE '%关键词%'"
-
address
: 发件人号码(需用单引号包裹)。 -
body LIKE '%关键词%'
: 短信内容包含的关键词。 -
输出结果会显示符合条件的短信的
_id
。
按时间戳筛选
adb shell content query --uri content://sms/inbox \
--projection _id,address,date \
--where "date > 1700000000000" # 时间戳(毫秒)
python代码实现短信的读取
import subprocess
from datetime import datetime
# 使用ADB命令获取短信
result = subprocess.run(['adb', 'shell', 'content', 'query', '--uri', 'content://sms/inbox'], stdout=subprocess.PIPE)
# 解析输出
output = result.stdout.decode('utf-8')
print(output)
打印结果是一条字符串数据,需要根据自己的目的解析一下。发现数据都是键值对的形式,写一个方法将键值对字符串转为字典再提取对应的信息。
def string_to_dict(input_string):
# 去掉字符串首尾的空格
input_string = input_string.strip()
# 将字符串按逗号分隔成多个键值对
pairs = input_string.split(", ")
# 创建一个空字典
result_dict = {}
# 遍历每个键值对
for pair in pairs:
# 如果键值对中包含等号,则分割成键和值
if "=" in pair:
key, value = pair.split("=", 1) # 从第一个等号处分割
key = key.strip() # 去掉键的首尾空格
value = value.strip() # 去掉值的首尾空格
# 如果值是数字,将其转换为整数或浮点数
if value.isdigit():
value = int(value)
elif value.replace('.', '', 1).isdigit() and value.count('.') < 2:
value = float(value)
# 如果值是 NULL,将其转换为 None
elif value.upper() == "NULL":
value = None
# 将键值对添加到字典中
result_dict[key] = value
return result_dict
for row in output.split('Row: ')[1:]:
data = string_to_dict(row)
address = data.get('address')
dt_sent = datetime.fromtimestamp(data.get('date_sent') / 1000)
formatted_time_send = dt_sent.strftime("%Y-%m-%d %H:%M:%S")
dt = datetime.fromtimestamp(data.get('date') / 1000)
formatted_time = dt.strftime("%Y-%m-%d %H:%M:%S")
service_center = data.get('service_center')
body = data.get('body')
print(f'{formatted_time} 收到 {address}({service_center}) 于 {formatted_time_send} 发送的短信信息:{body}\n')