python实现的登录和操作开心网脚本分享


Posted in Python onJuly 09, 2014

SNS什么的我是一直无爱的,这次蛋疼写了个登录开心网(kaixin001)并向所有好友发送站内消息的脚本。

开心网在登录的时候做了一些处理,并不传原始密码,从js分析到的结果是:登录时会生成一个随机的key,然后用这个key和原始密码进行xxtea加密,把加密后的结果再进行sha1加密。之后post这个key以及加密后的密码进行登录验证。

以下是很简陋的脚本内容:

#coding: utf-8
"""
开心网操作脚本

Author: piglei2007@gmail.com
Version: 1.0
"""
import re
import urllib
import urllib2
import random
import hashlib
import binascii
import cookielib
import simplejson

from xxtea import encrypt

LOGIN_URL = "http://www.kaixin001.com/login/login_api.php"
LOGIN_KEY_URL = "http://www.kaixin001.com/"
FRIEND_LIST_URL = "http://www.kaixin001.com/interface/suggestfriend.php"
MESSAGE_SEND_URL = "http://www.kaixin001.com/msg/post.php"

LOGIN_KEY_RE = re.compile(r"new\sEnLogin\('(.*?)'")

class LoginError(Exception):
  """
  登录失败抛出异常
  """

class Kaixin001User(object):
  """
  操作kaixin001,现有方法:
  
    get_login_key - 获得用户访问登录页面时分配的加密key
    
    get_rpassword - 获得经过xxtea以及sha1加密后的密码
    
    login - 登录
    
    get_friends_list - 获得所有好友,返回字典格式
    
    send_messages_to_all - 给所有好友发消息
  """
  
  def __init__(self, username, password):
    self.username = username
    self.password = password
    self.cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
    opener.addheaders = [
      ("User-agent", "Mozilla/5.0 (X11; U; FreeBSD i386; en-US; rv:1.9.1) Gecko/20090704 Firefox/3.5"),
      ("Accept", "*/*"),
      ("Host", "www.kaixin001.com")
    ]
    urllib2.install_opener(opener)
    
  def get_login_key(self):
    """
    获得登录时候的加密key
    """
    _temp = urllib2.urlopen(LOGIN_KEY_URL).read()
    key = LOGIN_KEY_RE.search(_temp).group(1)
    return key
    
  def login(self):
    """
    登录
    """
    login_key = self.get_login_key()
    rpassword = self.get_rpassword(self.password, login_key)
    login_params = {
      'email': self.username,
      'encypt': login_key,
      'rpasswd': rpassword,
      'url': '/home/',
      'ver': '1'      
    }
    req = urllib2.Request(LOGIN_URL, urllib.urlencode(login_params), {
      "Referer": "http://www.kaixin001.com/"
    })
    result = urllib2.urlopen(req).read()
    
    # 登录失败
    if "errno" in result:
      raise LoginError("登录失败,请检查用户名或密码")
    
    print "用户 %s 登录成功!" % self.username
    
    return 'ok'
  
  def get_friends_list(self):
    """
    获得所有好友列表
    """
    get_friends_params = {
      't': str(random.random()),
      'type': 'all',    
    }
    result = urllib2.urlopen(FRIEND_LIST_URL, urllib.urlencode(get_friends_params)).read()
    friends = simplejson.loads(result)
    
    print "你一共有 %s 位好友" % (len(friends) - 1)
    return friends
  
  def send_messages_to_all(self, message=''):
    """
    给所有好友发消息
    """
    friends = self.get_friends_list()
    send_params = {
      'attachment_cancel': '',
      'attachment_forwarding': '',	
      'attachment_random': '',
      'code': '',
      'content': message,
      'forward_thread': '',
      'rcode': '',
      'service': '0',
      'texttype': 'html',
      'uids': ",".join([str(f['uid']) for f in friends])   
    }
    result = urllib2.urlopen(MESSAGE_SEND_URL, urllib.urlencode(send_params))
    print result.geturl()
    print "消息发送成功"
    return 'ok'
    
  
  def get_rpassword(self, password, key):
    """
    获得加密后的密码
    """
    xxtea_pw = binascii.b2a_hex( encrypt(password, key) )
    r_password = hashlib.sha1(xxtea_pw).hexdigest()
    return r_password
  
if __name__ == '__main__':
  kxu = Kaixin001User(
    username = 'your_username',
    password = 'your_password'
  )
  kxu.login()
  kxu.send_messages_to_all("This message is send by Python.")

这是脚本中需要用到的xxtea算法的python实现(xxtea.py):

import struct
 
_DELTA = 0x9E3779B9 
 
def _long2str(v, w): 
  n = (len(v) - 1) << 2 
  if w: 
    m = v[-1] 
    if (m < n - 3) or (m > n): return '' 
    n = m 
  s = struct.pack('<%iL' % len(v), *v) 
  return s[0:n] if w else s 
 
def _str2long(s, w): 
  n = len(s) 
  m = (4 - (n & 3) & 3) + n 
  s = s.ljust(m, "\0") 
  v = list(struct.unpack('<%iL' % (m >> 2), s)) 
  if w: v.append(n) 
  return v 
 
def encrypt(str, key): 
  if str == '': return str 
  v = _str2long(str, True) 
  k = _str2long(key.ljust(16, "\0"), False) 
  n = len(v) - 1 
  z = v[n] 
  y = v[0] 
  sum = 0 
  q = 6 + 52 // (n + 1) 
  while q > 0: 
    sum = (sum + _DELTA) & 0xffffffff 
    e = sum >> 2 & 3 
    for p in xrange(n): 
      y = v[p + 1] 
      v[p] = (v[p] + ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z))) & 0xffffffff 
      z = v[p] 
    y = v[0] 
    v[n] = (v[n] + ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[n & 3 ^ e] ^ z))) & 0xffffffff 
    z = v[n] 
    q -= 1 
  return _long2str(v, False) 
 
def decrypt(str, key): 
  if str == '': return str 
  v = _str2long(str, False) 
  k = _str2long(key.ljust(16, "\0"), False) 
  n = len(v) - 1 
  z = v[n] 
  y = v[0] 
  q = 6 + 52 // (n + 1) 
  sum = (q * _DELTA) & 0xffffffff 
  while (sum != 0): 
    e = sum >> 2 & 3 
    for p in xrange(n, 0, -1): 
      z = v[p - 1] 
      v[p] = (v[p] - ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z))) & 0xffffffff 
      y = v[p] 
    z = v[n] 
    v[0] = (v[0] - ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[0 & 3 ^ e] ^ z))) & 0xffffffff 
    y = v[0] 
    sum = (sum - _DELTA) & 0xffffffff 
  return _long2str(v, True) 
 
if __name__ == "__main__": 
  print decrypt(encrypt('Hello XXTEA!', '16bytelongstring'), '16bytelongstring')
Python 相关文章推荐
Python中关于字符串对象的一些基础知识
Apr 08 Python
彻底理解Python list切片原理
Oct 27 Python
Python实现破解12306图片验证码的方法分析
Dec 29 Python
python实现word 2007文档转换为pdf文件
Mar 15 Python
Python实现的生产者、消费者问题完整实例
May 30 Python
python实现批量修改图片格式和尺寸
Jun 07 Python
深入了解和应用Python 装饰器 @decorator
Apr 02 Python
处理Selenium3+python3定位鼠标悬停才显示的元素
Jul 31 Python
python3.6中@property装饰器的使用方法示例
Aug 17 Python
python实现的爬取电影下载链接功能示例
Aug 26 Python
python构造函数init实例方法解析
Jan 19 Python
selenium设置浏览器为headless无头模式(Chrome和Firefox)
Jan 08 Python
python实现的一个火车票转让信息采集器
Jul 09 #Python
python的描述符(descriptor)、装饰器(property)造成的一个无限递归问题分享
Jul 09 #Python
Python中__init__和__new__的区别详解
Jul 09 #Python
Python中使用logging模块代替print(logging简明指南)
Jul 09 #Python
Python中的魔法方法深入理解
Jul 09 #Python
gearman的安装启动及python API使用实例
Jul 08 #Python
python实现跨文件全局变量的方法
Jul 07 #Python
You might like
php in_array 函数使用说明与in_array需要注意的地方说明
2010/04/13 PHP
yii的入口文件index.php中为什么会有这两句
2016/08/04 PHP
PHP页面间传递值和保持值的方法
2016/08/24 PHP
php生成HTML文件的类方法
2019/10/11 PHP
ie 调试javascript的工具
2009/04/29 Javascript
js 分栏效果实现代码
2009/08/29 Javascript
js 复制或插入Html的实现方法小结
2010/05/19 Javascript
JS验证日期的格式YYYY-mm-dd 具体实现
2013/06/29 Javascript
Javascript基础教程之if条件语句
2015/01/18 Javascript
Javascript的表单验证长度
2016/03/16 Javascript
nodejs的HTML分析利器node-jquery用法浅析
2016/11/08 NodeJs
SpringMVC+bootstrap table实例详解
2017/06/02 Javascript
详解vue项目打包步骤
2019/03/29 Javascript
nodejs dgram模块广播+组播的实现示例
2019/11/04 NodeJs
纯js实现无缝滚动功能代码实例
2020/02/21 Javascript
如何阻止移动端浏览器点击图片浏览
2020/08/29 Javascript
[03:06]3分钟带你回顾DOTA2完美盛典&完美大师赛
2017/12/06 DOTA
python网络编程学习笔记(五):socket的一些补充
2014/06/09 Python
Python实现基于KNN算法的笔迹识别功能详解
2018/07/09 Python
wtfPython—Python中一组有趣微妙的代码【收藏】
2018/08/31 Python
Python global全局变量函数详解
2018/09/18 Python
python pygame模块编写飞机大战
2018/11/20 Python
python 字符串常用函数详解
2019/09/11 Python
python yield关键词案例测试
2019/10/15 Python
Pytorch 计算误判率,计算准确率,计算召回率的例子
2020/01/18 Python
Python读取分割压缩TXT文本文件实例
2020/02/14 Python
Python文件操作及内置函数flush原理解析
2020/10/13 Python
亚瑟士美国官网:ASICS美国
2017/02/01 全球购物
决心书标准格式
2014/03/11 职场文书
学院党的群众路线教育实践活动整改方案
2014/10/04 职场文书
四风问题自我剖析材料
2014/10/07 职场文书
2014年财务部工作总结
2014/11/11 职场文书
乔迁之喜答谢词
2015/01/05 职场文书
2017寒假社会实践心得体会范文
2016/01/14 职场文书
python 实现定时任务的四种方式
2021/04/01 Python
动画《平凡职业成就世界最强》宣布制作OVA
2022/04/01 日漫