Python allows you to send and obtain verification codes for text messages and python text messages.

Source: Internet
Author: User

Python allows you to send and obtain verification codes for text messages and python text messages.

First, we will share with youPython background Method for sending text message verification CodesFor your reference, the specific content is as follows:

1. Generate a four-digit Verification Code

def createPhoneCode(session):   chars=['0','1','2','3','4','5','6','7','8','9']   x = random.choice(chars),random.choice(chars),random.choice(chars),random.choice(chars)   verifyCode = "".join(x)   session["phoneVerifyCode"] = {"time":int(time.time()), "code":verifyCode}   return verifyCode 

2. Send to external SMS interface (post method)

def sendTelMsg(msg, phoneID):   SendTelMsgUrl="http://www.810086.com.cn/jk.aspx"   params = {"zh":"china", "mm":"china@10086",         "hm":phoneID,"nr":msg,"sms_type":88}   postData=urllib.urlencode(params)   req = urllib2.Request(SendTelMsgUrl, postData)   req.add_header('Content-Type', "application/x-www-form-urlencoded")   respone = urllib2.urlopen(req)   res = respone.read()   return res 

The session parameter is the django urls. py background method passed in as request. session

3. Front-end js

$ ("Button [name = getVerifyBt]"). bind ("click", function () {var self = this; var userPhoneEl = $ ("input [name = phoneNum]"); var userPhone = $. trim (userPhoneEl. val (); if (userPhone = "") {alert ("Enter the number! "); Return;} $. get ("/getPhoneVerifyCode/" + userPhone + "/"). success (function (msg) {console.info (msg); var ddEl = $ (self ). siblings ("dd. showTag "); if (msg =" OK ") {ddEl. find ("span "). hide (); ddEl. find ("span [name = success]"). show ();} else {ddEl. find ("span "). hide (); ddEl. find ("span [name = error]"). show ();}}). error (function (msg) {console.info (msg) ;}); var step = 60; $ (this ). attr ("disabled", true); Publish (this).html ("resend" + step); var interThread = setInterval (function () {step-= 1; response (self).html ("resend" + step); if (step <= 0) {$ (self ). removeAttr ("disabled"); identifier (self).html ("Get Verification Code"); clearInterval (interThread) ;}, 1000 );});

The following is an introductionHow to obtain the mobile phone verification code through python interface Testing:

I encountered a problem during the Interface Test recently, that is, a very important interface needs to use the SMS verification code. Other interfaces depend on this verification code, if you do not have a text message verification code, you cannot test the following interface. To regularly verify that the online interface is normal without modifying the code, you can think of the following solution, if you have a better solution, you can share it with us.

After receiving the text message, Android sends a broadcast with the Action android. provider. Telephony. SMS_RECEIVED. Therefore, you only need to write a class to inherit BroadcastReceiver to easily listen to the text message.

package com.example.getsms;import android.content.BroadcastReceiver;import android.content.ContentResolver;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.telephony.SmsMessage;import android.text.TextUtils;import android.util.Log;public class SmsInterceptReceiver extends BroadcastReceiver {private final String TAG = "SmsRec";  private static final String SMS_EXTRA_NAME ="pdus";  @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String message = "";  Log.e(TAG, "free message " );      Bundle extras = intent.getExtras();    if ( extras != null ) {      try {      Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );        ContentResolver contentResolver = context.getContentResolver();                Log.e(TAG, "free message " );        for ( int i = 0; i < smsExtra.length; ++i ) {          SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);                    String body = sms.getMessageBody().toString();          message += body;        }                        Log.e(TAG, "free message : " + message);      } catch (Exception e) {      // TODO: handle exception      Log.e(TAG, e.getMessage());      }    }      }}

Register the receiver in AndroidManifest. xml:

 <receiver android:name=".SmsInterceptReceiver">     <intent-filter>     <action android:name="android.provider.Telephony.SMS_RECEIVED" />     </intent-filter>    </receiver>

Add permission:

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

Python code, mainly through adb log to obtain the SMS information intercepted by the apk package, and can be used after analysis.

_ Author _ = 'guozhenhua' # coding = utf-8import urllib2import OS, time # parse SMS verification code OS. system ("adb logcat-c") cmd = "adb logcat-d | findstr E/SmsRec" # time. sleep (30); while (1): smscode = OS. popen (cmd ). read () # print smscode if (smscode! = ""): Smscode = smscode. split ("Verification Code:") [1]. split (",") [0] break; print "Verification Code:" + smscode

The above is all the content of this article, which is rich in content, but there are also some shortcomings. I hope you will understand and learn and make progress together.

Articles you may be interested in:
  • Python image Verification Code
  • Python image verification code sharing
  • Example code of a Chinese Verification Code randomly generated by Python
  • Python adds recaptcha verification code for tornado
  • Example of a random Verification Code (Chinese Verification Code) generated by python
  • Example of using PyFetion to send text messages in python
  • Python calls the SMS cat control to implement the messaging function instance
  • Python generates Verification Code instances
  • Python generates a 6-digit Verification Code randomly.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.