ing 发表于 2021-1-24 15:41

腾讯云函数报错无效字符 invalid character in identifier

本帖最后由 ing 于 2021-1-24 16:10 编辑


运行环境python3.6








```

# coding: utf-8
# Author:p0ny
# Date :2021-01-20 02:14
# Tool :Notepad++ , IDLE
import base64,random,requests,json,hashlib,urllib3,time
from Crypto.Cipher import DES3
from Crypto.Util.Padding import pad, unpad
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random


def create_key_pair(size,random_generator):
    rsa = RSA.generate(size,random_generator)
    private_key = str(rsa.export_key(),'utf8')
    private_key = private_key.split('-\n').split('\n-')
    public_key = str(rsa.publickey().export_key(),'utf8')
    public_key = public_key.split('-\n').split('\n-')
    return public_key,private_key


def rsa_decrypt(input_string,private_key,random_generator):
    input_bytes = base64.b64decode(input_string)
    rsa_key = RSA.importKey("-----BEGIN RSA PRIVATE KEY-----\n"+private_key+"\n-----END RSA PRIVATE KEY-----")
    cipher = PKCS1_v1_5.new(rsa_key)
    return str(cipher.decrypt(input_bytes,random_generator),'utf-8')


def rsa_encrypt(input_string,public_key):
    rsa_key = RSA.importKey("-----BEGIN PUBLIC KEY-----\n"+public_key+"\n-----END PUBLIC KEY-----")
    cipher = PKCS1_v1_5.new(rsa_key)
    return str(base64.b64encode(cipher.encrypt(input_string.encode('utf-8'))),'utf-8')
   
def exchange_secret(blankUser,random_generator):
    """
    与完美校园服务器交换RSA加密的公钥,并取得sessionId
    :return:
    """
    resp = requests.post(
      "https://server.17wanxiao.com/campus/cam_iface46/exchangeSecretkey.action",
      headers={
            "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 5.1.1; HUAWEI MLA-AL10 Build/HUAWEIMLA-AL10)",
      },
      json={
            "key": blankUser["rsaKey"]["public"]#pub
      },
      verify=False
    )

    session_info = json.loads(
      rsa_decrypt(resp.text.encode(resp.apparent_encoding), blankUser["rsaKey"]["private"],random_generator)
    )
    blankUser["sessionId"] = session_info["session"]
    blankUser["appKey"] = session_info["key"][:24]

   
def create_blank_user(random_generator):
    """
    当传入的已登录设备信息不可用时,虚拟一个空的未登录设备
    :return: 空设备信息
    """
    rsa_keys = create_key_pair(1024,random_generator)
    return {
      'appKey': '',
      'sessionId': '',
      'exchangeFlag': True,
      'login': False,
      'serverPublicKey': '',
      # 'deviceId': str(random.randint(999999999999999, 9999999999999999)),
      'wanxiaoVersion': 10462101,
      'rsaKey': {
            'private': rsa_keys,
            'public': rsa_keys
      }
    }
   
def des_3_encrypt(string, key,iv):
    cipher = DES3.new(key, DES3.MODE_CBC,iv.encode("utf-8"))
    ct_bytes = cipher.encrypt(pad(string.encode('utf8'), DES3.block_size))
    ct = base64.b64encode(ct_bytes).decode('utf8')
    return ct
   
   
def object_encrypt(object_to_encrypt,key,iv="66666666"):
    return des_3_encrypt(json.dumps(object_to_encrypt),key,iv)


def login(phone,pwd,blankUser,systemInfo):
    """
    使用账号密码登录完美校园APP
    :param phone: 完美校园APP绑定的手机号码
    :param password: 完美校园密码
    :return:
    """
    password_list = []
    for i in pwd:
      password_list.append(des_3_encrypt(i, blankUser["appKey"], "66666666"))
    login_args = {
      "appCode": "M002",
      "deviceId": systemInfo['IMEI'],
      "netWork": "wifi",
      "password": password_list,
      "qudao": "guanwang",
      "requestMethod": "cam_iface46/loginnew.action",
      
      #"shebeixinghao": "MLA-AL10",
      "shebeixinghao": systemInfo['shebeixinghao'],
      
      "systemType": "android",
      
      #"telephoneInfo": "5.1.1",
      "telephoneInfo": systemInfo['telephoneInfo'],

      
      #"telephoneModel": "HUAWEI MLA-AL10",
      "telephoneModel": systemInfo['telephoneModel'],
      
      "type": "1",
      "userName": phone,
      "wanxiaoVersion": 10462101,
      "yunyingshang": "07"
    }
    upload_args = {
      "session": blankUser["sessionId"],
      "data": object_encrypt(login_args, blankUser["appKey"])
    }
    LoginFlag = requests.post(
      "https://server.17wanxiao.com/campus/cam_iface46/loginnew.action",
      headers={"campusSign": hashlib.sha256(json.dumps(upload_args).encode('utf-8')).hexdigest(),
      'User-Agent':'Mozilla/5.0 (Linux; Android ' + systemInfo['telephoneInfo'] +'; ' + systemInfo['shebeixinghao'] +'Build/'+ systemInfo['telephoneModel'] + '; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0' },
      json=upload_args,
      verify=False
    ).json()
    # print(LoginFlag)

    if not LoginFlag['result_']:
      return False,LoginFlag['message_']
   



    data = {
      "appClassify": "DK",
      "token": blankUser["sessionId"]
    }

   
    requests.post("https://reportedh5.17wanxiao.com/api/clock/school/getUserInfo", data=data)
    # requests.post("https://reportedh5.17wanxiao.com/api/clock/school/open", data=data)
    return True,blankUser["sessionId"] # 返回token



def checkIn(token, id, systemInfo):
    """
    打卡
    """
    post_url = 'https://reportedh5.17wanxiao.com/sass/api/epmpics'
    headers = {
    'Host': 'reportedh5.17wanxiao.com',
    'Connection': 'keep-alive',
    'Content-Length': '1375',
    'Accept': 'application/json, text/plain, */*',
    'Origin': 'https://reportedh5.17wanxiao.com',
    'User-Agent':'Mozilla/5.0 (Linux; Android ' + systemInfo['telephoneInfo'] +'; ' + systemInfo['shebeixinghao'] +'Build/'+ systemInfo['telephoneModel'] + '; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.157 Mobile Safari/537.36 Wanxiao/5.3.4',
    'Content-Type': 'application/json;charset=UTF-8',
    'Referer': 'https://reportedh5.17wanxiao.com/health/index.html?templateid=pneumonia&businessType=epmpics&customerId=18018&systemType=Android&UAinfo=wanxiao&versioncode=10534101&token={}'.format(token),
    'Accept-Encoding':'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'X-Requested-With': 'com.newcapec.mobile.ncp'
    }
   

   
   
   
    # 这里的地址信息最好抓包验证
    # 1. 抓下提交地址信息替换
    # 2. 将   "gpsType":1,"token":"94616a9d-a9aa-4d47-aa94-6da6862af7c8"【不管那一串码是什么,替换成后面那样子,】}}替换成   "gpsType":1,"token":token}}
    json_load = {"businessType":"epmpics","method":"submitUpInfo","jsonData":{"deptStr":{"deptid":215300,"text":"学生(人工智能学院)-软件技术(大数据应用)-19软件技术1班"},"areaStr":"{\"streetNumber\":\"28号\",\"street\":\"育才中路\",\"district\":\"麻章区\",\"city\":\"湛江市\",\"province\":\"广东省\",\"town\":\"\",\"pois\":\"湛江市水质免费检测点\",\"lng\":110.34032499999996,\"lat\":21.274375980202826,\"address\":\"麻章区育才中路28号湛江市水质免费检测点\",\"text\":\"广东省-湛江市\",\"code\":\"\"}","reportdate":1611061439444,"customerid":"18018","deptid":215300,"source":"app","templateid":"pneumonia","stuNo":"20190003826","username":"冯宇聪","phonenum":"","userid":"19257283","updatainfo":[{"propertyname":"isConfirmed","value":"否"},{"propertyname":"isdefinde","value":"否"},{"propertyname":"symptom","value":"均无以上情况。"},{"propertyname":"isTransitArea","value":"正常"},{"propertyname":"sfddgr","value":"正常"},{"propertyname":"jkzks","value":"否"},{"propertyname":"isTransitProvince","value":""},{"propertyname":"hcdzsj","value":"13420134428"},{"propertyname":"emergencyContact","value":"陈金英"},{"propertyname":"mergencyPeoplePhone","value":"15975982063"},{"propertyname":"assistRemark","value":""}],"gpsType":1,"token":token}}
   
    # 以上地址信息抓包对比
    # 以上地址信息抓包对比
    # 以上地址信息抓包对比


      
    try:
      response = requests.post(url = post_url,data=json.dumps(json_load),headers=headers, verify = False)
      mark_msg = response.json()['msg']# 成功
      mark_code = response.json()['code']# 10000
      mark_data = response.json()['data']# 1

      text = ('msg = ' + mark_msg + '\t'+ 'data = '+ str(mark_data) +'\t'+ 'code = ' + str(mark_code))
         
    except Exception:
      text = response.json()
      
      
    return text


# 使用脚本需要知道以下信息:
#1. 完美校园 app 登陆账号   
#2. 完美校园 app 登陆密码




def main_handler(event, content):
    # 如果 SendVX = 1,使用 巴法云 推送微信消息,如果 SendVX = 0,不推送
    SendVX = 0 # 设置是否使用 微信消息推送服务
    sec = random.randint(10,50)
    time.sleep(sec)# 随机睡眠 10 ~ 50秒之间
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)






# ===========================主要是 修改 这里==========================================================

    # 设备型号
    shebeixinghao = "JKM-AL00a"

    # 安卓版本
    telephoneInfo = "8.1.0"

    # 手机型号
    telephoneModel = "HUAWEIJKM-AL00a"

    # IMEI
    IMEI = '1233456784234'
      
    # 手机号
    phone = '13800000000'   # phone = '13800138000'

    # 登陆密码【忘记密码可以在完美校园app中修改】
    pwd = '123456'# pwd = '13800138000'
# =====================================================================================================
   



   
   
    systemInfo = {
    # 设备型号
    "shebeixinghao":shebeixinghao,
    # 安卓版本
    "telephoneInfo" : telephoneInfo,

    # 手机型号
    "telephoneModel" : telephoneModel,
   
    # IMEI
    'IMEI' : IMEI
    }

    random_generator = Random.new().read
    blankUser = create_blank_user(random_generator)
    exchange_secret(blankUser,random_generator)
    flag,token = login(phone,pwd,blankUser,systemInfo)
    if flag:
      
      checkStatus = checkIn(token,SendVX,systemInfo)
    else:
      print(token)
      checkStatus = token

    if SendVX:
      headers = {
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'

      }
      requests.get('http://api.bemfa.com/api/wechat/v1/weget.php?type=2&uid=巴法云秘钥&device=完美校园打卡&msg={}'.format(checkStatus),headers=headers)
    return checkStatus

```

ing 发表于 2021-1-24 15:44

我复制代码到txt文档另存为UTF-8再复制过去也报错

巛丶傀儡 发表于 2021-1-24 15:50

Jack2002 发表于 2021-1-24 17:07

我这儿部署成功,
Response:
{"errorCode":-1,"errorMessage":"Traceback (most recent call last):\nFile \"/var/runtime/python3/bootstrap.py\", line 133, in init_handler\n    func_handler = get_func_handler(file.rsplit(\".\", 1), func)\nFile \"/var/runtime/python3/bootstrap.py\", line 159, in get_func_handler\n    mod = imp.load_module(mname, *imp.find_module(mname))\nFile \"/var/lang/python3/lib/python3.6/imp.py\", line 234, in load_module\n    return load_source(name, filename, file)\nFile \"/var/lang/python3/lib/python3.6/imp.py\", line 172, in load_source\n    module = _load(spec)\nFile \"\u003cfrozen importlib._bootstrap\u003e\", line 675, in _load\nFile \"\u003cfrozen importlib._bootstrap\u003e\", line 655, in _load_unlocked\nFile \"\u003cfrozen importlib._bootstrap_external\u003e\", line 678, in exec_module\nFile \"\u003cfrozen importlib._bootstrap\u003e\", line 205, in _call_with_frames_removed\nFile \"/var/user/index.py\", line 6, in \u003cmodule\u003e\n    from Crypto.Cipher import DES3\nModuleNotFoundError: No module named 'Crypto'","statusCode":443}

Jack2002 发表于 2021-1-24 17:13

本帖最后由 Jack2002 于 2021-1-24 17:14 编辑

分享几点小技巧:

头部编码通用(兼容)写法: # -*- coding: utf-8 -*-
缩进符要统一,空格和制表符只用一种,别混用

Jack2002 发表于 2021-1-24 17:57

本帖最后由 Jack2002 于 2021-1-24 17:59 编辑

遇到个问题,云上安装pycrypto失败, 更新了PIP、setuptools,还是失败!

Command "/var/lang/python3/bin/python3 -u -c "import setuptools, tokenize;
__file__='/tmp/pip-install-v94u28lz/pycrypto/setup.py';
f=getattr(tokenize, 'open', open)(__file__);
code=f.read().replace('\r\n', '\n');
f.close();
exec(compile(code, __file__, 'exec'))"
install --record /tmp/pip-record-ni5lf3u2/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-v94u28lz/pycrypto/
页: [1]
查看完整版本: 腾讯云函数报错无效字符 invalid character in identifier