Skip to content

Instantly share code, notes, and snippets.

@arturvt
Last active September 16, 2020 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturvt/04261c74f0cba9284511 to your computer and use it in GitHub Desktop.
Save arturvt/04261c74f0cba9284511 to your computer and use it in GitHub Desktop.
A simple Python 2.7 app that read all non read messages from Android (rooted) devices. Also a method to mark as read. Fully tested with Android 5.0 device.
#!/usr/bin/env python
"""
This file contains a method to fetch all unread SMS messages from an android device and returns a dict with result.
@author: Artur Tenorio - arturvt@gmail.com
"""
from datetime import datetime
import os
import pipes
import subprocess
ADB_BINARY = "adb"
SMS_DB = "/data/data/com.android.providers.telephony/databases/mmssms.db"
SELECT_SMS_SQL = 'SELECT _id, address, date, body FROM sms WHERE read=0;'
UPDATE_READ_SQL = 'UPDATE sms SET read=1 WHERE _id in (%d);'
def get_unread_messages():
"""
Looks for all unread messages and retuns a dict with id, address, date and body message.
:return list: A list with All unread messages in as dict.
"""
cmd = 'adb shell "su -c sqlite3 %s %s"' % (SMS_DB, pipes.quote(SELECT_SMS_SQL))
print cmd
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = p.communicate()
result = []
for msg in out.replace('\r', '').strip('\n').split('\n'):
msg = msg.split('|')
result.append(dict(id=msg[0], sender=msg[1],
date_time=str(datetime.fromtimestamp(int(int(msg[2])/1000))), message=msg[3]))
return result
def set_read_message(msg_id):
"""
Sets a message identified by msg_id to read.
:param msg_id:
:return:
"""
cmd = 'adb shell "su -c sqlite3 %s %s"' % (SMS_DB, pipes.quote(UPDATE_READ_SQL % msg_id))
os.system(cmd)
def main():
result = get_unread_messages()
for r in result:
print r
if __name__ == '__main__':
main()
@KarthickSathya22
Copy link

how to run this code

@arturvt
Copy link
Author

arturvt commented Jun 8, 2020

it must be a rooted device, and adb must be installed and configured.

@linghu258
Copy link

Hi, I just tested out the codes. There is an error ? TypeError: a byte-like object is required, not "str"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment