RPA解决:python GSM 模块 - 电脑接收短信

学Python,用RPA

艺赛旗RPA2020.1版本 正在免费下载使用中,欢迎下载使用

www.i-search.com.cn/index.html?from=line1

RPA解决:python GSM 模块 - 电脑接收短信
前言:
最近做了一个需求,需要接收手机短信验证码。因此我这里考虑到了 GSM 模块。

RPA解决:python GSM 模块 - 电脑接收短信
目前电信已退 2g 网,联通正在退,只剩下移动。不过大家以后可以直接购买 4g 的模块进行使用。

  1. 安装依赖
    pip install pyserial

  2. 窗口连接
    import serial
    s = serial.Serial("/dev/ttyUSB0")

  3. 打电话
    s.write(“ATD10086;\r\n”.encode())

  4. 发短信
    设置短信模式为 PDU
    s.write(b’AT+CMGF=0\r\n’)
    设置短信编码
    s.write(b’AT+CSCS=“UCS2”\r\n’)
    手机号码 16 进制 unicode 码
    s.write(‘AT+CMGS=“00310030003000380036”\r\n’.encode())
    短信内容 16 进制 unicode 码
    s.write(‘00680065006c006c006f00204e16754c’.encode())
    发送代码
    s.write(b’\x1A\r\n’)

  5. 读取短信
    import re
    读取所有短信
    s.write(b’AT+CMGL=“ALL”\r\n’)
    获取全部返回
    res = s.read()
    while True:
    count = s.inWaiting()
    if count == 0:
    break
    res += s.read(count)
    匹配短信文本
    msg_list = re.findall(’+CMGL: (\d+),“REC READ”,"(.?)","","(.?)"\r\n(.*?)\r\n’, res.decode())
    msg_list = [list(i) for i in msg_list]
    for msg in msg_list:
    msg[1] = unicode2str(msg[1])
    msg[-1] = unicode2str(msg[-1])
    print(msg_list)

  6. 字符串转 16 进制 unicode 码
    def str2unicode(text):
    code = ‘’
    for i in text:
    hex_i = hex(ord(i))
    if len(hex_i) == 4:
    code += hex_i.replace(‘0x’, ‘00’)
    else:
    code += hex_i.replace(‘0x’, ‘’)
    return code

  7. 16 进制 unicode 码转字符串
    def unicode2str(code):
    text = ‘’
    tmp = ‘’
    for i in range(len(code)):
    tmp += code[i]
    if len(tmp) == 4:
    text += “\\u” + tmp
    tmp = ‘’
    text = eval(f’"{text}"’)
    return text