Python implementation to send and get SMS verification code

Source: Internet
Author: User
First for everyone to share python implementation to send SMS verification code backstage method, for your reference, the specific contents are as follows

1. Generate 4-bit digital 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}   

2. Send to external SMS interface (POST mode)

def sendtelmsg (msg, Phoneid):   sendtelmsgurl= "http://www.810086.com.cn/jk.aspx"   params = {"zh": "China", "MM" : "china@10086",         "HM":p Honeid, "nr": Msg, "Sms_type":   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 ()   

Where the session parameter is the Django urls.py backend method to request.session the incoming

3, front-end JS

$ ("BUTTON[NAME=GETVERIFYBT]"). Bind ("click", Function () {var = this;   var Userphoneel = $ ("input[name=phonenum]");   var userphone = $.trim (Userphoneel.val ()); if (Userphone = = "") {alert ("Please fill in 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);   $ (this). HTML ("Resend" +step);     var interthread = setinterval (function () {step-=1;     $ (self). HTML ("Resend" +step);       if (step <=0) {$ (self). REMOVEATTR ("Disabled");       $ (self). HTML ("Get Verification Code");     Clearinterval (Interthread);       }}, 1000); }); 

The following is a description of the Python solution interface test to obtain a mobile phone verification code problem method :

Recently in the interface test encountered a problem, is that there is a very important interface to use the SMS Verification code, and other interfaces are dependent on this verification code, if no SMS verification code can not test the following interface, so in order to verify the timing of the interface is normal, and do not modify the code, So think of the following solutions, if you have a better plan to share with each other.

Android sends an action-Android.provider.Telephony.SMS_RECEIVED broadcast after it receives a text message, so we just need to write a class-inheriting broadcastreceiver to easily listen to the SMS.

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 the Androidmanifest.xml:

 
 
       
  
             
  
       
 
  

Add Permissions:

 
  

Python code, mainly through the ADB log to get the SMS information captured by the APK package, and then after analysis can be used.

__author__ = ' Guozhenhua ' #coding =utf-8import urllib2import os,time# parsing SMS Verification Code os.system ("adb logcat-c") cmd= "adb logcat-d |findstr E/smsrec "#time. Sleep (1):  smscode= os.popen (cmd). Read ()  #print smscode  if (smscode! = ""):    smscode=smscode.split ("Verification Code:") [1].split (",") [0]    Break;print "Captcha is:" +smscode

The above is the whole content of this article, the content is very rich, but there are some shortcomings, I hope you understand, and common learning progress.

  • Related Article

    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.