`
daniel_tu
  • 浏览: 184200 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

两个不错的Python Fetion的东西

阅读更多

两个不错的Python Fetion的东西,现在我还不懂,转贴到这里,以后再研究研究。。

1. It's so large, so I have to copy hyperlink here.
http://code.google.com/p/pytool/source/browse/trunk/PyFetion/PyFetion.py
Home page: http://cocobear.info/blog/2008/12/03/write-fetion-with-python-pyfetion/

2. Copy the source code here.
#----------------------------------------------------------------------------------------------------------------------
#!/usr/bin/env python
# -*- coding: gbk -*-

import binascii
import hashlib
import re
import StringIO
import urllib
import urllib2
import uuid
import xml.etree.ElementTree as ET

from getpass import getpass
from optparse import OptionParser

FETION_URL = 'http://221.130.45.203/ht/sd.aspx'
FETION_SIPC = '221.130.45.203:8080'
FETION_LOGIN_URL = 'https://nav.fetion.com.cn/ssiportal/SSIAppSignIn.aspx'
FETION_CONFIG_URL = 'http://nav.fetion.com.cn/nav/getsystemconfig.aspx'
FETION_SIPP = 'SIPP'

DEBUG = False

class Fetion:
    ssic = ''
    sid = ''
    domain = ''

    call = 0
    seq = 0
    guid = None
    contacts = []

    def __init__(self, mobileno, password):
        self.mobileno = mobileno
        self.password = password
        self.http_tunnel = FETION_URL
        self.sipc_proxy = FETION_SIPC

    def login(self):
        re_ssic = re.compile('ssic=(.*?);')
        re_sid = re.compile('sip:(\d+)@(.+);')
       
        login_url = FETION_LOGIN_URL
        data = {'mobileno' : self.mobileno, 'pwd' : self.password}
        conn = urllib2.urlopen(login_url, urllib.urlencode(data))

        # Get ssic
        headers = str(conn.headers)
        res = re_ssic.findall(headers)
        if res:
            ssic = res[0]
           
        response = conn.read()

        # Get other attribs from response
        xmldoc = ET.XML(response)
        status_code = xmldoc.attrib['status-code']
        user_node = xmldoc.find('user')
        uri = user_node.attrib['uri']
        mobile_no = user_node.attrib['mobile-no']
        user_status = user_node.attrib['user-status']

        # get sid and domain from uri
        res = re_sid.findall(uri)
        if res:
            sid, domain = res[0]

        self.ssic = ssic
        self.sid = sid
        self.domain = domain

    def http_register(self):
        arg= '<args><device type="PC" version="0" client-version="3.1.0480" /><caps value="fetion-im;im-session;temp-group" /><events value="contact;permission;system-message" /><user-info attributes="all" /><presence><basic value="400" desc="" /></presence></args>'

        _call = self.next_call()

        # request 1
        _url = self.next_url('i')
        response = self.send_request(_url, FETION_SIPP)

        # request 2
        msg = self.create_sip_data('R fetion.com.cn SIP-C/2.0', (('F',self.sid), ('I',_call), ('Q','1 R')), arg) + FETION_SIPP
        _url = self.next_url()
        response = self.send_request(_url, msg)

        # request 3
        _url = self.next_url()
        response = self.send_request(_url, FETION_SIPP)
        re_nonce = re.compile('nonce="(\w+)"')
        nonce = re_nonce.findall(response)[0]

        # request 4
        _cnonce = self.calc_cnonce() # calculate cnonce
        _response = self.calc_response(nonce, _cnonce) # calculate response
        _salt = self.calc_salt() # calculate salt
        msg = self.create_sip_data('R fetion.com.cn SIP-C/2.0', (('F', self.sid), ('I',_call), ('Q', '2 R'), ('A', 'Digest algorithm="SHA1-sess",response="%s",cnonce="%s",salt="%s"' % (_response, _cnonce, _salt))), arg) + FETION_SIPP
        _url = self.next_url()
        response = self.send_request(_url, msg)

        # request 5
        _url = self.next_url()
        response = self.send_request(_url, FETION_SIPP)

    def get_contacts_list(self):
        arg = '<args><contacts><buddy-lists /><buddies attributes="all" /><mobile-buddies attributes="all" /><chat-friends /><blacklist /></contacts></args>'
        _call = self.next_call()
        msg = self.create_sip_data('S fetion.com.cn SIP-C/2.0', (('F',self.sid), ('I',_call), ('Q','1 S'), ('N','GetContactList')), arg) + FETION_SIPP
        _url = self.next_url()
        self.send_request(_url, msg)
        _url = self.next_url()
        response = self.send_request(_url, FETION_SIPP)

        re_contacts = re.compile('uri="(sip[^"]+)"')
        res = re_contacts.findall(response)

        return res

    def get_contacts_info(self, contacts_list):
        if contacts_list:
            arg = '<args><contacts attributes="all">'
            for contact in contacts_list:
                arg += '<contact uri="%s" />' % contact
            arg += '</contacts></args>'

            _call = self.next_call()
            msg = self.create_sip_data('S fetion.com.cn SIP-C/2.0', (('F',self.sid), ('I',_call), ('Q','1 S'), ('N','GetContactsInfo')), arg) + FETION_SIPP
            _url = self.next_url()
            self.send_request(_url, msg)
            _url = self.next_url()
            response = self.send_request(_url, FETION_SIPP)

            re_info = re.compile('uri="([^"]+)".*?mobile-no="([^"]+)"')
            res = re_info.findall(response)

            for contact in contacts_list:
                if not filter(lambda x: x[0] == contact, res):
                    res.append((contact, ''))

            self.contacts = res

    def get_contact_sid(self, info):
        sid = None

        if info[:4] == 'sip:':
            sid = filter(lambda x: x[0] == info, self.contacts)
        elif len(info) == 9:
            sid = filter(lambda x: x[0][4:13] == info, self.contacts)
        elif len(info) == 11:
            sid = filter(lambda x: x[1] == info, self.contacts)

        return sid and sid[0][0] or None

    def get_system_config(self):
        msg = '<config><user mobile-no="%s" /><client type="PC" version="3.2.0540" platform="W5.1" /><servers version="0" /><service-no version="0" /><parameters version="0" /><hints version="0" /><http-applications version="0" /></config>' % self.mobileno
        request = urllib2.Request(FETION_CONFIG_URL, data=msg)
        conn = urllib2.urlopen(request)
        response = conn.read()

        xmldoc = ET.parse(StringIO.StringIO(response))
        result = xmldoc.find('//http-tunnel').text
        if result:
            self.http_tunnel = result
        result = xmldoc.find('//sipc-proxy').text
        if result:
            self.sipc_proxy = result

    def send_sms(self, to, content):
        _call = self.next_call()
        msg = self.create_sip_data('M fetion.com.cn SIP-C/2.0', (('F',self.sid), ('I',_call), ('Q','1 M'), ('T',to), ('N','SendSMS')), content) + FETION_SIPP
        _url = self.next_url()
        self.send_request(_url, msg)
        _url = self.next_url()
        response = self.send_request(_url, FETION_SIPP)

        if 'Send SMS OK' in response:
            return True
        else:
            return False

    def send_cat_sms(self, to, content):
        _call = self.next_call()
        msg = self.create_sip_data('M fetion.com.cn SIP-C/2.0', (('F',self.sid), ('I',_call), ('Q','1 M'), ('T',to), ('N','SendCatSMS')), content) + FETION_SIPP
        _url = self.next_url()
        self.send_request(_url, msg)
        _url = self.next_url()
        response = self.send_request(_url, FETION_SIPP)

        if 'Send SMS OK' in response:
            return True
        else:
            return False

    def send_request(self, url, data):
        if not self.guid:
            self.guid = str(uuid.uuid1())
        headers = {
                'User-Agent' : 'IIC2.0/pc 3.1.0480',
                'Cookie':'ssic=%s' % self.ssic,
                'Content-Type' : 'application/oct-stream',
                'Pragma' : 'xz4BBcV%s' % self.guid,
                }
        request = urllib2.Request(url, headers=headers, data=data)
        conn = urllib2.urlopen(request)
        response = conn.read()
        if DEBUG:
            print 'DEBUG'.center(78, '*')
            print 'URL:', url
            print 'Data:', data
            print 'Response:', response
            print 'DEBUG'.center(78, '*')
            print

        return response

    def create_sip_data(self, invite, fields, arg=''):
        sip = invite + '\r\n'
        for k, v in fields:
            sip += '%s: %s\r\n' % (k, v)
        sip += 'L: %s\r\n\r\n%s' % (len(arg), arg)

        return sip


    def next_call(self):
        self.call += 1

        return self.call

    def next_url(self, t='s'):
        self.seq += 1

        return '%s?t=%s&i=%s' % (self.http_tunnel, t, self.seq)

    def calc_cnonce(self):
        md5 = hashlib.md5()
        md5.update(str(uuid.uuid1()))

        return md5.hexdigest().upper()

    def hash_password(self):
        salt = '%s%s%s%s' % (chr(0x77), chr(0x7A), chr(0x6D), chr(0x03))
        sha1 = hashlib.sha1()
        sha1.update(self.password)
        src = salt + sha1.digest()
        sha1 = hashlib.sha1()
        sha1.update(src)

        return '777A6D03' + sha1.hexdigest().upper()

    def calc_response(self, nonce, cnonce):
        hashpassword = self.hash_password()
        binstr = binascii.unhexlify(hashpassword[8:])
        sha1 = hashlib.sha1()
        sha1.update('%s:%s:%s' % (self.sid, self.domain, binstr))
        key = sha1.digest()
        md5 = hashlib.md5()
        md5.update('%s:%s:%s' % (key, nonce, cnonce))
        h1 = md5.hexdigest().upper()
        md5 = hashlib.md5()
        md5.update('REGISTER:%s' % self.sid)
        h2 = md5.hexdigest().upper()
        md5 = hashlib.md5()
        md5.update('%s:%s:%s' % (h1, nonce, h2))

        return md5.hexdigest().upper()

    def calc_salt(self):
        return self.hash_password()[:8]
   
def SendSMS(mobile,password,to,body):
   
    fetion = Fetion(mobile, password)
    fetion.get_system_config()
    fetion.login()
    fetion.http_register()
    fetion.get_contacts_info(fetion.get_contacts_list())

    if to:
        sid = fetion.get_contact_sid(to)
        if not sid:
            sid = to

        if sid:          
            if fetion.send_cat_sms(sid, body):
                print 'Sent SMS'
            else:
                print 'Error occurs'
   
def main():
    # create a options parser
    parser = OptionParser()
    parser.add_option('-m', '--mobile', dest='mobile', type='string',
                      help='mobile phone number')
    parser.add_option('-p', '--password', dest='password', type='string',
                      help='login password')
    parser.add_option('-t', '--to', dest='to', type='string',
                      help='SMS to')
    parser.add_option('-b', '--body', dest='body', type='string',
                      help='SMS body')
    parser.add_option('-l', '--long-body', dest='lbody', type='string',
                      help='SMS long body')

    (options, args) = parser.parse_args()

    # handle options
    if not options.mobile:
        parser.error('-m option is required')

    mobile = options.mobile
    if not options.password:
        password = getpass()
    else:
        password = options.password

    fetion = Fetion(mobile, password)
    fetion.get_system_config()
    fetion.login()
    fetion.http_register()
    fetion.get_contacts_info(fetion.get_contacts_list())

    if options.to:
        sid = fetion.get_contact_sid(options.to)

        if not sid:
            sid = options.to

        if sid:
            if options.body:
                if fetion.send_sms(sid, options.body):
                    print 'Sent SMS'
                else:
                    print 'Error occurs'
            elif options.lbody:
                if fetion.send_cat_sms(sid, options.lbody):
                    print 'Sent SMS'
                else:
                    print 'Error occurs'

if __name__ == '__main__':
    body_unicode = u"Send mail content"
    body_unicode *= 10
    body_utf = body_unicode.encode('utf-8')
    #s.encode('utf-8')
    #s.encode('utf8')
    #s = unicode(s,"cp936")
    SendSMS('13557715959','550505','13551505755',body_utf)

#--------------------------------------------------------------------------------------------------------------------------

分享到:
评论

相关推荐

    PythonFetion客户端

    PythonFetion客户端是一款利用Python编程语言开发的飞信(Fetion)应用程序。飞信是中国移动推出的一款即时通讯服务,允许用户通过短信、互联网等方式进行免费或低成本的通信。这款Python实现的客户端旨在为用户提供...

    Fetion.rar_fetion_fetion 3_fetion java_fetion3

    在这个压缩包文件中,我们看到的是一个针对飞信3.0版本的修改版,名为"Fetion 3_fetion java_fetion3",特别强调了"HighlinZhu"的修改,以及加入了“震动”功能和进行了“窗口优化”。 1. **飞信3.0基础功能**: -...

    fetion.rar_fetion_visual c

    【标题】"fetion.rar_fetion_visual c" 涉及的IT知识点主要集中在飞信(Fetion)的客户端开发以及使用Visual C#编程语言实现通过Web URL发送短信的功能。 飞信是中国移动推出的一款即时通讯软件,允许用户通过网络...

    PHP Fetion 类 可以用

    标题中的“PHP Fetion 类 可以用”指的是在PHP编程语言中存在一个Fetion类,这个类可能被用于处理与中国移动飞信(Fetion)服务相关的交互。飞信是中国移动推出的一种即时通讯工具,允许用户通过手机或电脑进行文字...

    开源 Fetion api java

    标题“开源 Fetion api java”指的是一个开源的Java API,用于与Fetion(飞信)服务进行交互。Fetion是一种由中国移动推出的即时通讯软件,允许用户通过互联网或手机发送短信、语音消息以及进行语音通话。这个API...

    fetion.rar_fetion

    标题中的“fetion.rar_fetion”暗示了一个与飞信相关的项目,飞信是一款由中国移动推出的即时通讯软件,允许用户免费发送短信、进行语音聊天等。在这个项目中,使用了Python编程语言来实现发送飞信的功能。描述提到...

    飞信接口java Fetion Api java

    final Fetion fetion = new Fetion("phone","password"); fetion.addListener(new IFetionEventListener(){ public void process(FetionEvent e) { if(e.getFirstLine()!=null && e.getFirstLine...

    java飞信接口,FetionApi(无license限制,附可运行代码例子)

    fetion.sendSms2SelfPhone("给自己发个试哈^_^..."); //fetion.logout(); } } 为了怕玩的人多了,移动服务器发现,请大家测试自己的手机玩,尽量少发 一切后果自负... 无奈啊.......... 欢迎到这 ...

    PHP飞信(PHPFetion)发送类v1.2

    1. 需要包含进你的程序的文件只有一个:PHPFetion.php。如: require 'PHPFetion.php'; 2. 调用方法如: $fetion = new PHPFetion('13500001111', '123123'); // 手机号、飞信密码 $fetion-&gt;send('13500001111', ...

    fetion mrp

    fetion mrp

    linux版fetion_for x64

    Linux版的"Fetion_for_x64"是一款专为64位Linux操作系统设计的飞信客户端,它允许用户在Linux环境下发送短信至手机。飞信,全称中国移动飞信,是中国移动推出的一种融合语音(IVR)、短信、GPRS等多种通信方式的即时...

    FETION.rar_Java fetion_download free fetion_fetion j_fetion jar_

    "Fetion.jar"是一个基于Java平台的应用程序,它利用Java的可移植性,使得该飞信客户端可以在多种操作系统上运行,包括但不限于Windows、Linux和Mac OS。Java应用程序通常以.jar(Java Archive)格式打包,这样可以将...

    Fetion.rar_fetion_love

    综合以上分析,这个"Fetion.rar_fetion_love"压缩包是一个结合了飞信服务与情感元素的打包资源,包含了一个可能的飞信客户端安装程序和一个来自pudn.com的文本文件。用户可以通过解压和运行Fetion.exe来体验与飞信...

    Fetion_3.4.3_ty.jar

    Fetion_3.4.3_ty.jar

    fetion服务端(windows\linux)、PHP短信发送模块

    这里的"Fetion服务端(windows\linux)"表明该服务端实现了跨操作系统平台的支持,既能在Windows系统上运行,也能在Linux系统上运行,这通常需要采用跨平台的开发工具和语言,如Java或Python。 2. **PHP短信发送...

    Fetion.rar_fetion_fetion Visual Basic_飞信

    在“Fetion.rar_fetion_fetion Visual Basic_飞信”这个压缩包中,我们可以看到与飞信相关的编程资源,特别是与Visual Basic的结合,这表明它是关于如何使用Visual Basic来控制和操作飞信的教程或者代码示例。...

    飞信 fetion_2008

    飞信是中国移动推出的一款通信软件,全称为"Fetion",在2008年时的版本为"Fetion_2008"。这款应用旨在提供便捷、高效的即时通讯服务,尤其注重融合手机与互联网的通讯体验。下面将详细阐述飞信的主要功能、发展历程...

    占用内存小的简约版Fetion-可以网上给移动用户免费发短信

    标签“fetion”和“飞信”进一步确认了我们讨论的主题,这两个标签通常与移动通信和免费短信服务关联,也是飞信品牌的主要标识。 至于压缩包子文件的文件名称“LibFetion”,这很可能是飞信客户端的库文件或者动态...

    fetion.zip_fetion php

    而“fetion.zip_fetion php”这个标题暗示我们这里有一个使用PHP编写的飞信客户端或者服务端的程序。 PHP是一种广泛使用的开源服务器端脚本语言,特别适合于Web开发,可以嵌入到HTML中。在这个场景中,"fetion.php"...

    Fetion.zip_fetion CSharp

    标题"Fetion.zip_fetion CSharp"指出这是一个与飞信相关的C#编程项目,而“飞信”是中国电信推出的一款即时通讯软件,允许用户通过网络免费向中国移动、联通、电信的手机用户发送短信。"CSharp"表示这里的实现是使用...

Global site tag (gtag.js) - Google Analytics