Python实现的Google IP 可用性检测脚本


Posted in Python onApril 23, 2015

需要 Python 3.4+,一个参数用来选择测试搜索服务还是 GAE 服务。测试 GAE 服务的话需要先修改开头的两个变量。从标准输入读取 IP 地址或者 IP 段(形如 192.168.0.0/16)列表,每行一个。可用 IP 输出到标准输出。实时测试结果输出到标准错误。50 线程并发。

checkgoogleip

#!/usr/bin/env python3
 
import sys
from ipaddress import IPv4Network
import http.client as client
from concurrent.futures import ThreadPoolExecutor
import argparse
import ssl
import socket
 
# 先按自己的情况修改以下几行
APP_ID = 'your_id_here'
APP_PATH = '/fetch.py'
 
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations('/etc/ssl/certs/ca-certificates.crt')
 
class HTTPSConnection(client.HTTPSConnection):
 def __init__(self, *args, hostname=None, **kwargs):
  self._hostname = hostname
  super().__init__(*args, **kwargs)
 
 def connect(self):
  super(client.HTTPSConnection, self).connect()
 
  if self._tunnel_host:
   server_hostname = self._tunnel_host
  else:
   server_hostname = self._hostname or self.host
   sni_hostname = server_hostname if ssl.HAS_SNI else None
 
  self.sock = self._context.wrap_socket(self.sock,
                     server_hostname=sni_hostname)
  if not self._context.check_hostname and self._check_hostname:
   try:
    ssl.match_hostname(self.sock.getpeercert(), server_hostname)
   except Exception:
    self.sock.shutdown(socket.SHUT_RDWR)
    self.sock.close()
    raise
 
def check_ip_p(ip, func):
 if func(ip):
  print(ip, flush=True)
 
def check_for_gae(ip):
 return _check(APP_ID + '.appspot.com', APP_PATH, ip)
 
def check_for_search(ip):
 return _check('www.google.com', '/', ip)
 
def _check(host, path, ip):
 for chance in range(1,-1,-1):
  try:
   conn = HTTPSConnection(
    ip, timeout = 5,
    context = context,
    hostname = host,
   )
   conn.request('GET', path, headers = {
    'Host': host,
   })
   response = conn.getresponse()
   if response.status < 400:
    print('GOOD:', ip, file=sys.stderr)
   else:
    raise Exception('HTTP Error %s %s' % (
     response.status, response.reason))
   return True
  except KeyboardInterrupt:
   raise
  except Exception as e:
   if isinstance(e, ssl.CertificateError):
    print('WARN: %s is not Google\'s!' % ip, file=sys.stderr)
    chance = 0
   if chance == 0:
    print('BAD :', ip, e, file=sys.stderr)
    return False
   else:
    print('RE :', ip, e, file=sys.stderr)
 
def main():
 parser = argparse.ArgumentParser(description='Check Google IPs')
 parser.add_argument('service', choices=['search', 'gae'],
           help='service to check')
 args = parser.parse_args()
 func = globals()['check_for_' + args.service]
 
 count = 0
 with ThreadPoolExecutor(max_workers=50) as executor:
  for l in sys.stdin:
   l = l.strip()
   if '/' in l:
    for ip in IPv4Network(l).hosts():
     executor.submit(check_ip_p, str(ip), func)
     count += 1
   else:
    executor.submit(check_ip_p, l, func)
    count += 1
 print('%d IP checked.' % count)
 
if __name__ == '__main__':
 main()
Python 相关文章推荐
使用python统计文件行数示例分享
Feb 21 Python
零基础写python爬虫之神器正则表达式
Nov 06 Python
使用Python的Treq on Twisted来进行HTTP压力测试
Apr 16 Python
python统计cpu利用率的方法
Jun 02 Python
python基础之入门必看操作
Jul 26 Python
用Python3创建httpServer的简单方法
Jun 04 Python
Python错误处理操作示例
Jul 18 Python
Python 将Matrix、Dict保存到文件的方法
Oct 30 Python
python 运用Django 开发后台接口的实例
Dec 11 Python
Django学习之文件上传与下载
Oct 06 Python
python访问hdfs的操作
Jun 06 Python
Python实现列表拼接和去重的三种方式
Jul 02 Python
Python3.2中的字符串函数学习总结
Apr 23 #Python
Python与Redis的连接教程
Apr 22 #Python
Python实现的数据结构与算法之快速排序详解
Apr 22 #Python
利用Fn.py库在Python中进行函数式编程
Apr 22 #Python
Python实现的数据结构与算法之基本搜索详解
Apr 22 #Python
Python实现的数据结构与算法之链表详解
Apr 22 #Python
Python实现的数据结构与算法之双端队列详解
Apr 22 #Python
You might like
DC动画电影《黑暗正义联盟》曝预告 5月5日上线数字平台
2020/04/09 欧美动漫
西德产收音机
2021/03/01 无线电
PHP 编程的 5个良好习惯
2009/02/20 PHP
取得单条网站评论以数组形式进行输出
2014/07/28 PHP
JavaScript错误处理
2015/02/03 Javascript
js+html5实现可在手机上玩的拼图游戏
2015/07/17 Javascript
js实现仿网易点击弹出提示同时背景变暗效果
2015/08/13 Javascript
WordPress 单页面上一页下一页的实现方法【附代码】
2016/03/10 Javascript
jQuery实现判断控件是否显示的方法
2017/01/11 Javascript
JavaScript基于DOM操作实现简单的数学运算功能示例
2017/01/16 Javascript
微信小程序登录态控制深入分析
2017/04/12 Javascript
addeventlistener监听scroll跟touch(实例讲解)
2017/08/04 Javascript
vue.js评论发布信息可插入QQ表情功能
2017/08/08 Javascript
详解VUE 数组更新
2017/12/16 Javascript
利用nginx + node在阿里云部署https的步骤详解
2017/12/19 Javascript
详解async/await 异步应用的常用场景
2019/05/13 Javascript
Python 文件和输入输出小结
2013/10/09 Python
Python中的面向对象编程详解(下)
2015/04/13 Python
Python构造自定义方法来美化字典结构输出的示例
2016/06/16 Python
Python3实现对列表按元组指定列进行排序的方法分析
2018/12/22 Python
Python TCP通信客户端服务端代码实例
2019/11/21 Python
python socket通信编程实现文件上传代码实例
2019/12/14 Python
Python操作注册表详细步骤介绍
2020/02/05 Python
Python中私有属性的定义方式
2020/03/05 Python
使用python批量转换文件编码为UTF-8的实现
2020/04/03 Python
TensorFlow的reshape操作 tf.reshape的实现
2020/04/19 Python
金讯Java笔试题目
2013/06/18 面试题
销售文员岗位职责
2013/11/29 职场文书
酒店人事专员岗位职责
2013/12/19 职场文书
诚信的演讲稿范文
2014/05/12 职场文书
动物科学专业求职信
2014/07/27 职场文书
踏青活动策划方案
2014/08/19 职场文书
小学数学继续教育研修日志
2015/11/13 职场文书
图文详解nginx日志切割的实现
2022/01/18 Servers
分布式架构Redis中有哪些数据结构及底层实现原理
2022/03/13 Redis
漫画「日和酱的要求是绝对的」第3卷封面公开
2022/03/21 日漫