python查看删除你微信的账号
#应用环境:python2.7 #!/usr/bin/env python
# coding=utf-8
from __future__ import print_function import os
try:
from urllib import urlencode, quote_plus
except ImportError:
from urllib.parse import urlencode, quote_plus try:
import urllib2 as wdf_urllib
from cookielib import CookieJar
except ImportError:
import urllib.request as wdf_urllib
from http.cookiejar import CookieJar import re
import time
import xml.dom.minidom
import json
import sys
import math
import subprocess
import ssl
import thread DEBUG = False MAX_GROUP_NUM = 35 # 每组人数
INTERFACE_CALLING_INTERVAL = 20 # 接口调用时间间隔, 间隔太短容易出现"操作太频繁", 会被限制操作半小时左右
MAX_PROGRESS_LEN = 50 QRImagePath = os.path.join(os.getcwd(), 'qrcode.jpg') tip = 0
uuid = '' base_uri = ''
redirect_uri = ''
push_uri = '' skey = ''
wxsid = ''
wxuin = ''
pass_ticket = ''
deviceId = 'e000000000000000' BaseRequest = {} ContactList = []
My = []
SyncKey = [] try:
xrange
range = xrange
except:
# python 3
pass def responseState(func, BaseResponse):
ErrMsg = BaseResponse['ErrMsg']
Ret = BaseResponse['Ret']
if DEBUG or Ret != 0:
print('func: %s, Ret: %d, ErrMsg: %s' % (func, Ret, ErrMsg)) if Ret != 0:
return False return True def getRequest(url, data=None):
try:
data = data.encode('utf-8')
except:
pass
finally:
return wdf_urllib.Request(url=url, data=data) def getUUID():
global uuid url = 'https://login.weixin.qq.com/jslogin'
params = {
'appid': 'wx782c26e4c19acffb',
'fun': 'new',
'lang': 'zh_CN',
'_': int(time.time()),
} request = getRequest(url=url, data=urlencode(params))
response = wdf_urllib.urlopen(request)
data = response.read().decode('utf-8', 'replace') # print(data) # window.QRLogin.code = 200; window.QRLogin.uuid = "oZwt_bFfRg==";
regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
pm = re.search(regx, data) code = pm.group(1)
uuid = pm.group(2) if code == '':
return True return False def showQRImage():
global tip url = 'https://login.weixin.qq.com/qrcode/' + uuid
params = {
't': 'webwx',
'_': int(time.time()),
} request = getRequest(url=url, data=urlencode(params))
response = wdf_urllib.urlopen(request) tip = 1 f = open(QRImagePath, 'wb')
f.write(response.read())
f.close() if sys.platform.find('darwin') >= 0:
subprocess.call(['open', QRImagePath])
elif sys.platform.find('linux') >= 0:
subprocess.call(['xdg-open', QRImagePath])
else:
os.startfile(QRImagePath) print('请使用微信扫描二维码以登录') def waitForLogin():
global tip, base_uri, redirect_uri, push_uri url = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s' % (
tip, uuid, int(time.time())) request = getRequest(url=url)
response = wdf_urllib.urlopen(request)
data = response.read().decode('utf-8', 'replace') # print(data) # window.code=500;
regx = r'window.code=(\d+);'
pm = re.search(regx, data) code = pm.group(1) if code == '': # 已扫描
print('成功扫描,请在手机上点击确认以登录')
tip = 0
elif code == '': # 已登录
print('正在登录...')
regx = r'window.redirect_uri="(\S+?)";'
pm = re.search(regx, data)
redirect_uri = pm.group(1) + '&fun=new'
base_uri = redirect_uri[:redirect_uri.rfind('/')] # push_uri与base_uri对应关系(排名分先后)(就是这么奇葩..)
services = [
('wx2.qq.com', 'webpush2.weixin.qq.com'),
('qq.com', 'webpush.weixin.qq.com'),
('web1.wechat.com', 'webpush1.wechat.com'),
('web2.wechat.com', 'webpush2.wechat.com'),
('wechat.com', 'webpush.wechat.com'),
('web1.wechatapp.com', 'webpush1.wechatapp.com'),
]
push_uri = base_uri
for (searchUrl, pushUrl) in services:
if base_uri.find(searchUrl) >= 0:
push_uri = 'https://%s/cgi-bin/mmwebwx-bin' % pushUrl
break # closeQRImage
if sys.platform.find('darwin') >= 0: # for OSX with Preview
os.system("osascript -e 'quit app \"Preview\"'")
elif code == '': # 超时
pass
# elif code == '400' or code == '500': return code def login():
global skey, wxsid, wxuin, pass_ticket, BaseRequest request = getRequest(url=redirect_uri)
response = wdf_urllib.urlopen(request)
data = response.read().decode('utf-8', 'replace') # print(data) doc = xml.dom.minidom.parseString(data)
root = doc.documentElement for node in root.childNodes:
if node.nodeName == 'skey':
skey = node.childNodes[0].data
elif node.nodeName == 'wxsid':
wxsid = node.childNodes[0].data
elif node.nodeName == 'wxuin':
wxuin = node.childNodes[0].data
elif node.nodeName == 'pass_ticket':
pass_ticket = node.childNodes[0].data # print('skey: %s, wxsid: %s, wxuin: %s, pass_ticket: %s' % (skey, wxsid,
# wxuin, pass_ticket)) if not all((skey, wxsid, wxuin, pass_ticket)):
return False BaseRequest = {
'Uin': int(wxuin),
'Sid': wxsid,
'Skey': skey,
'DeviceID': deviceId,
} return True def webwxinit(): url = base_uri + \
'/webwxinit?pass_ticket=%s&skey=%s&r=%s' % (
pass_ticket, skey, int(time.time()))
params = {
'BaseRequest': BaseRequest
} request = getRequest(url=url, data=json.dumps(params))
request.add_header('ContentType', 'application/json; charset=UTF-8')
response = wdf_urllib.urlopen(request)
data = response.read() if DEBUG:
f = open(os.path.join(os.getcwd(), 'webwxinit.json'), 'wb')
f.write(data)
f.close() data = data.decode('utf-8', 'replace') # print(data) global ContactList, My, SyncKey
dic = json.loads(data)
ContactList = dic['ContactList']
My = dic['User']
SyncKey = dic['SyncKey'] state = responseState('webwxinit', dic['BaseResponse'])
return state def webwxgetcontact(): url = base_uri + \
'/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s' % (
pass_ticket, skey, int(time.time())) request = getRequest(url=url)
request.add_header('ContentType', 'application/json; charset=UTF-8')
response = wdf_urllib.urlopen(request)
data = response.read() if DEBUG:
f = open(os.path.join(os.getcwd(), 'webwxgetcontact.json'), 'wb')
f.write(data)
f.close() # print(data)
data = data.decode('utf-8', 'replace') dic = json.loads(data)
MemberList = dic['MemberList'] # 倒序遍历,不然删除的时候出问题..
SpecialUsers = ["newsapp", "fmessage", "filehelper", "weibo", "qqmail", "tmessage", "qmessage", "qqsync", "floatbottle", "lbsapp", "shakeapp", "medianote", "qqfriend", "readerapp", "blogapp", "facebookapp", "masssendapp",
"meishiapp", "feedsapp", "voip", "blogappweixin", "weixin", "brandsessionholder", "weixinreminder", "wxid_novlwrv3lqwv11", "gh_22b87fa7cb3c", "officialaccounts", "notification_messages", "wxitil", "userexperience_alarm"]
for i in range(len(MemberList) - 1, -1, -1):
Member = MemberList[i]
if Member['VerifyFlag'] & 8 != 0: # 公众号/服务号
MemberList.remove(Member)
elif Member['UserName'] in SpecialUsers: # 特殊账号
MemberList.remove(Member)
elif Member['UserName'].find('@@') != -1: # 群聊
MemberList.remove(Member)
elif Member['UserName'] == My['UserName']: # 自己
MemberList.remove(Member) return MemberList def createChatroom(UserNames):
MemberList = [{'UserName': UserName} for UserName in UserNames] url = base_uri + \
'/webwxcreatechatroom?pass_ticket=%s&r=%s' % (
pass_ticket, int(time.time()))
params = {
'BaseRequest': BaseRequest,
'MemberCount': len(MemberList),
'MemberList': MemberList,
'Topic': '',
} request = getRequest(url=url, data=json.dumps(params))
request.add_header('ContentType', 'application/json; charset=UTF-8')
response = wdf_urllib.urlopen(request)
data = response.read().decode('utf-8', 'replace') # print(data) dic = json.loads(data)
ChatRoomName = dic['ChatRoomName']
MemberList = dic['MemberList']
DeletedList = []
BlockedList = []
for Member in MemberList:
if Member['MemberStatus'] == 4: # 被对方删除了
DeletedList.append(Member['UserName'])
elif Member['MemberStatus'] == 3: # 被加入黑名单
BlockedList.append(Member['UserName']) state = responseState('createChatroom', dic['BaseResponse']) return ChatRoomName, DeletedList, BlockedList def deleteMember(ChatRoomName, UserNames):
url = base_uri + \
'/webwxupdatechatroom?fun=delmember&pass_ticket=%s' % (pass_ticket)
params = {
'BaseRequest': BaseRequest,
'ChatRoomName': ChatRoomName,
'DelMemberList': ','.join(UserNames),
} request = getRequest(url=url, data=json.dumps(params))
request.add_header('ContentType', 'application/json; charset=UTF-8')
response = wdf_urllib.urlopen(request)
data = response.read().decode('utf-8', 'replace') # print(data) dic = json.loads(data) state = responseState('deleteMember', dic['BaseResponse'])
return state def addMember(ChatRoomName, UserNames):
url = base_uri + \
'/webwxupdatechatroom?fun=addmember&pass_ticket=%s' % (pass_ticket)
params = {
'BaseRequest': BaseRequest,
'ChatRoomName': ChatRoomName,
'AddMemberList': ','.join(UserNames),
} request = getRequest(url=url, data=json.dumps(params))
request.add_header('ContentType', 'application/json; charset=UTF-8')
response = wdf_urllib.urlopen(request)
data = response.read().decode('utf-8', 'replace') # print(data) dic = json.loads(data)
MemberList = dic['MemberList']
DeletedList = []
BlockedList = []
for Member in MemberList:
if Member['MemberStatus'] == 4: # 被对方删除了
DeletedList.append(Member['UserName'])
elif Member['MemberStatus'] == 3: # 被加入黑名单
BlockedList.append(Member['UserName']) state = responseState('addMember', dic['BaseResponse']) return DeletedList, BlockedList def syncKey():
SyncKeyItems = ['%s_%s' % (item['Key'], item['Val'])
for item in SyncKey['List']]
SyncKeyStr = '|'.join(SyncKeyItems)
return SyncKeyStr def syncCheck():
url = push_uri + '/synccheck?'
params = {
'skey': BaseRequest['Skey'],
'sid': BaseRequest['Sid'],
'uin': BaseRequest['Uin'],
'deviceId': BaseRequest['DeviceID'],
'synckey': syncKey(),
'r': int(time.time()),
} request = getRequest(url=url + urlencode(params))
response = wdf_urllib.urlopen(request)
data = response.read().decode('utf-8', 'replace') # print(data) # window.synccheck={retcode:"0",selector:"2"}
regx = r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}'
pm = re.search(regx, data) retcode = pm.group(1)
selector = pm.group(2) return selector def webwxsync():
global SyncKey url = base_uri + '/webwxsync?lang=zh_CN&skey=%s&sid=%s&pass_ticket=%s' % (
BaseRequest['Skey'], BaseRequest['Sid'], quote_plus(pass_ticket))
params = {
'BaseRequest': BaseRequest,
'SyncKey': SyncKey,
'rr': ~int(time.time()),
} request = getRequest(url=url, data=json.dumps(params))
request.add_header('ContentType', 'application/json; charset=UTF-8')
response = wdf_urllib.urlopen(request)
data = response.read().decode('utf-8', 'replace') # print(data) dic = json.loads(data)
SyncKey = dic['SyncKey'] state = responseState('webwxsync', dic['BaseResponse'])
return state def heartBeatLoop():
while True:
selector = syncCheck()
if selector != '':
webwxsync()
time.sleep(1) def main(): try:
ssl._create_default_https_context = ssl._create_unverified_context opener = wdf_urllib.build_opener(
wdf_urllib.HTTPCookieProcessor(CookieJar()))
opener.addheaders = [
('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36')]
wdf_urllib.install_opener(opener)
except:
pass if not getUUID():
print('获取uuid失败')
return print('正在获取二维码图片...')
showQRImage()
time.sleep(1) while waitForLogin() != '':
pass os.remove(QRImagePath) if not login():
print('登录失败')
return if not webwxinit():
print('初始化失败')
return MemberList = webwxgetcontact() print('开启心跳线程')
thread.start_new_thread(heartBeatLoop, ()) MemberCount = len(MemberList)
print('通讯录共%s位好友' % MemberCount) ChatRoomName = ''
result = []
d = {}
for Member in MemberList:
d[Member['UserName']] = (Member['NickName'].encode(
'utf-8'), Member['RemarkName'].encode('utf-8'))
print('开始查找...')
group_num = int(math.ceil(MemberCount / float(MAX_GROUP_NUM)))
for i in range(0, group_num):
UserNames = []
for j in range(0, MAX_GROUP_NUM):
if i * MAX_GROUP_NUM + j >= MemberCount:
break
Member = MemberList[i * MAX_GROUP_NUM + j]
UserNames.append(Member['UserName']) # 新建群组/添加成员
if ChatRoomName == '':
(ChatRoomName, DeletedList, BlockedList) = createChatroom(
UserNames)
else:
(DeletedList, BlockedList) = addMember(ChatRoomName, UserNames) # todo BlockedList 被拉黑列表 DeletedCount = len(DeletedList)
if DeletedCount > 0:
result += DeletedList # 删除成员
deleteMember(ChatRoomName, UserNames) # 进度条
progress = MAX_PROGRESS_LEN * (i + 1) / group_num
print('[', '#' * progress, '-' * (MAX_PROGRESS_LEN - progress), ']', end=' ')
print('新发现你被%d人删除' % DeletedCount)
for i in range(DeletedCount):
if d[DeletedList[i]][1] != '':
print(d[DeletedList[i]][0] + '(%s)' % d[DeletedList[i]][1])
else:
print(d[DeletedList[i]][0]) if i != group_num - 1:
print('正在继续查找,请耐心等待...')
# 下一次进行接口调用需要等待的时间
time.sleep(INTERFACE_CALLING_INTERVAL)
# todo 删除群组 print('\n结果汇总完毕,20s后可重试...')
resultNames = []
for r in result:
if d[r][1] != '':
resultNames.append(d[r][0] + '(%s)' % d[r][1])
else:
resultNames.append(d[r][0]) print('---------- 被删除的好友列表(共%d人) ----------' % len(result))
# 过滤emoji
resultNames = map(lambda x: re.sub(r'<span.+/span>', '', x), resultNames)
if len(resultNames):
print('\n'.join(resultNames))
else:
print("无")
print('---------------------------------------------') # windows下编码问题修复
# http://blog.csdn.net/heyuxuanzee/article/details/8442718 class UnicodeStreamFilter: def __init__(self, target):
self.target = target
self.encoding = 'utf-8'
self.errors = 'replace'
self.encode_to = self.target.encoding def write(self, s):
if type(s) == str:
s = s.decode('utf-8')
s = s.encode(self.encode_to, self.errors).decode(self.encode_to)
self.target.write(s) if sys.stdout.encoding == 'cp936':
sys.stdout = UnicodeStreamFilter(sys.stdout) if __name__ == '__main__': print('本程序的查询结果可能会引起一些心理上的不适,请小心使用...')
main()
print('回车键退出...')
python查看删除你微信的账号的更多相关文章
- 我用 Python 找出了删除我微信的所有人并将他们自动化删除了
1. 概述 不知你是否遇到过在微信上给通讯录中的某个人发消息,结果出现了这一幕: 平时一直认为自己的心里素质过硬,不过遇到这种情况 ... 在我缓了半个钟头(半分钟)之后,缓缓拿出了手机,打开微信,找 ...
- PJzhang:查看你的微信、QQ、新浪微博都授权给过谁
猫宁!!! 个人信息的保护,需要时刻关注,不能有丝毫懈怠. 保护个人信息,有两个方向,一个是减少个人信息外泄,另一个是上传大量鱼龙杂的个人信息,难以分辨,混淆视听. 这里不谈第二个, ...
- 微信公众账号开发教程(四)自定义菜单(含实例源码)——转自http://www.cnblogs.com/yank/p/3418194.html
微信公众账号开发教程(四)自定义菜单 请尊重作者版权,如需转载,请标明出处. 应大家强烈要求,将自定义菜单功能课程提前. 一.概述: 如果只有输入框,可能太简单,感觉像命令行.自定义菜单,给我们提供了 ...
- Zabbix微信个人账号告警
前言: 最近研究zabbix告警,网上看了帖子有各式各样姿势:电话语音告警,邮件告警,短信告警,微信公众号告警等等等..姿势五花八门,真是纠结. 电话语音告警,短信告警首先pass 前者花钱,后者通过 ...
- 微信公众账号【iOSDevTip】推出新栏目【看大牛】
首先你须要关注微信公众账号[iOSDevTip] 基于微信公众平台数据分析.非常easy发现.移动端project师都喜欢关注互联网创业资讯.都说.一个不关注互联网创业的iOS开发不是一个合格的互联网 ...
- 一支烟的时间导致他错失女神,Python查看撤回消息,力挽狂澜!
2011年1月21日 微信(WeChat) 是腾讯公司于2011年1月21日推出的一个为智能终端提供即时通讯服务的免费应用程序,由张小龙所带领的腾讯广州研发中心产品团队打造 .在互联网飞速发展的下.民 ...
- python 多线程删除MySQL表
一.需求分析 在<python 统计MySQL表信息>这篇博客中,链接如下: https://www.cnblogs.com/xiao987334176/p/9901692.html 已经 ...
- 【python】10分钟教你用python下载和拼接微信好友头像图片
前言 相信微信大家是用得再多也不过了.那么,对于python+微信,又能玩出什么新的花样呢?下面小编就给大家带来一个好玩的东西.用python下载所有的微信好友的头像,然后拼接成一张大图.这样,大家就 ...
- linux+apache+mod_python+wechat_sdk搭建微信公共账号服务器
linux+apache+mod_python+wechat_sdk搭建微信公共账号服务器 转载请注明本文原作者:FignerLiu PRE 最近尝试了下使用python搭建微信公共账号服务器,实现了 ...
随机推荐
- Droppable(放置)组件
.加载方式 //class 加载方式 <div id="dd" class="easyui-droppable" data-options="a ...
- iOS_SN_LLDB常用命令
有一次因为封装一个控件,UI能正常显示就是不能点击,一点击就崩溃,而且异常断点也无法捕捉,把Xcode的僵尸对象打开,每次崩溃就打印一个地址,最后就必须根据地址寻找对象,可以使用frame varia ...
- poj2486
题目大意:给出一个树,每个节点有一个值,问从1开始走走k步最多能遍历到最大的值的和:dp[i][j][k] 当i为零是表示如果从j点开始遍历以j为跟的子树,走k步后回到原点的最大值.dp[i][j][ ...
- poj3685 二分套二分
F - 二分二分 Crawling in process... Crawling failed Time Limit:6000MS Memory Limit:65536KB 64bit ...
- [转]Windows与Linux系统下的库文件介绍
什么是库 库文件是一些预先编译好的函数的集合,那些函数都是按照可再使用的原则编写的.它们通常由一组互相关联的用来完成某项常见工作的函数构成,从本质上来说库是一种可执行代码的二进制形式,可以被操作系 ...
- 转自http://blog.slogra.com/post-13.html,关闭centos虚拟机的蜂鸣声
相信对经常在虚拟机做实验的人来说,每次按tab来补全命令的时候是最痛苦的,这个时候是最让人想把 电脑的蜂鸣器给拆下来,让我们来关闭这个烦人的东西吧. 在centos系统下的方法 1.临时解决办法:以 ...
- .net转php laraval框架学习系列(二)项目实战---Models
上一篇已经介绍开发环境的搭建,如果有问题可以在文章后留言. 这篇将从项目实战开发,一步一步了解laravel框架. 在开发mvc项目时,models都是第一步. 下面就从建模开始. 实体关系图 由于不 ...
- LINUX VPS 查看系统信息命令
系统# uname -a # 查看内核/操作系统/CPU信息# head -n 1 /etc/issue # 查看操作系统版本# cat /proc/cpuinfo # 查看CPU信息# hostna ...
- dedecms文章的更新时间问题 每次更改文章时间变成最新的
dedecms 每次更改文章,更新时间这里每次改了后再来看又变成当前最新时间的了. 解决方法: 查找后台目录的 templets/article_edit.htm 这个文件. 然后打开,查找如下代码: ...
- Python Udp Socket
socket(套接字),传输层通信的端点,由IP和端口号组成(IP,Port),可以通过socket精确地找到服务器上的进程并与之通信 python2.6实现,基于AF_INET(网络套接字) 类型S ...