Skip to content

Instantly share code, notes, and snippets.

@piotrmaslanka
Last active August 24, 2020 14:39
Show Gist options
  • Save piotrmaslanka/efac069a17f06505ae280d7d521f4e0d to your computer and use it in GitHub Desktop.
Save piotrmaslanka/efac069a17f06505ae280d7d521f4e0d to your computer and use it in GitHub Desktop.
Script to receive SMS-es from an AT command operated GSM modem.

list_sms

A tool to automatically receive SMS-es from SIM card of a AT-command enabled GSM modem running over your UART (or USB, as long as it's reachable as a serial device, it's fair game), write them to a file and then delete them from the SIM card, since the SIM card doesn't have infinite space.

Run it without any modifiers to delete the SMS-es, run it with any modifier, preferably --dont-delete not to delete them from the SIM card.

"""
A script to list and delete received SMS-es on an UART attached AT-command GSM modem.
Author: Piotr Maślanka <pmaslanka@smok.co>
Copyright 2020 (c) SMOK sp. z o. o. Some rights reserved.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
"""
import serial
import time
import re
import sys
SEPARATOR = re.compile(r'\+CMGL\:\s(\d+)\,\"(.*?)\"\,\"(.*?)\",(\,{0,1})\"(.*?)\"\r\n(.*?)\r\n')
if __name__ == '__main__':
ser = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=5)
ser.write(b'AT+CMGL="ALL"\r')
data = bytearray()
while True:
time.sleep(1)
readed = ser.read(1024)
if not readed:
break
else:
data += readed
print(repr(data))
smses = []
entries = list(SEPARATOR.findall(data.decode('utf8')))
print(entries)
for msg_id, rec_mode, phone_no, who, when, content in entries:
smses.append('%s %s\n' % (phone_no, content.replace('\r', "\\r").replace('\n', '\\n')))
if not smses:
print('No SMS-es detected!')
sys.exit(0)
f_out = open('sms.txt', 'a')
f_out.write(''.join(smses))
f_out.close()
print(repr(smses))
if len(sys.argv) == 1:
for message_id, rec_mode, phone_no, who, when, content in entries:
ser.write(b'AT+CMGD='+message_id.encode('utf8')+b',0\r')
started_at = time.monotonic()
data = bytearray()
while time.monotonic() - started_at < 2:
time.sleep(0.2)
data = data + ser.read(1024)
if b'\r\r\nOK\r\n' in data:
print('Deleted ', message_id, 'with', repr(data))
break
else:
print('Failure to CMGD')
else:
print('Not deleting')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment