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实现的石头剪子布代码分享
Aug 22 Python
举例讲解Python中的迭代器、生成器与列表解析用法
Mar 20 Python
利用python生成一个导出数据库的bat脚本文件的方法
Dec 30 Python
win7 x64系统中安装Scrapy的方法
Nov 18 Python
python使用pdfminer解析pdf文件的方法示例
Dec 20 Python
Python解析命令行读取参数之argparse模块
Jul 26 Python
python实现通过flask和前端进行数据收发
Aug 22 Python
python pptx复制指定页的ppt教程
Feb 14 Python
Python读取文件内容为字符串的方法(多种方法详解)
Mar 04 Python
python爬虫实现获取下一页代码
Mar 13 Python
浅谈django 模型类使用save()方法的好处与注意事项
Mar 28 Python
Python参数传递实现过程及原理详解
May 14 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
生成静态页面的PHP类
2006/07/15 PHP
phpfans留言版用到的install.php
2007/01/04 PHP
laravel项目利用twemproxy部署redis集群的完整步骤
2018/05/11 PHP
在修改准备发的批量美化select+可修改select时,在非IE下发现了几个问题
2007/01/09 Javascript
javascript下给元素添加事件的方法与代码
2007/08/13 Javascript
JavaScript 判断浏览器类型及版本
2009/02/21 Javascript
js中判断数字\字母\中文的正则表达式 (实例)
2012/06/29 Javascript
javascript使用数组的push方法完成快速排序
2014/09/15 Javascript
BootStrap中Datepicker控件带中文的js文件
2016/08/10 Javascript
JS实现重新加载当前页面或者父页面的几种方法
2016/11/30 Javascript
jQuery中 bind的用法简单介绍
2017/02/13 Javascript
Bootstrap Table 在指定列中添加下拉框控件并获取所选值
2017/07/31 Javascript
基于LayUI分页和LayUI laypage分页的使用示例
2017/08/02 Javascript
Angular 5.x 学习笔记之Router(路由)应用
2018/04/08 Javascript
vue实现同一个页面可以有多个router-view的方法
2018/09/20 Javascript
Next.js项目实战踩坑指南(笔记)
2018/11/29 Javascript
vue动态绘制四分之三圆环图效果
2019/09/03 Javascript
vue-router之实现导航切换过渡动画效果
2019/10/31 Javascript
Vue解析带html标签的字符串为dom的实例
2019/11/13 Javascript
基于Cesium绘制抛物弧线
2020/11/18 Javascript
Python中文字符串截取问题
2015/06/15 Python
详解Python中的文件操作
2016/08/28 Python
Python 'takes exactly 1 argument (2 given)' Python error
2016/12/13 Python
Python语言生成水仙花数代码示例
2017/12/18 Python
将python安装信息加入注册表的示例
2019/11/20 Python
从Pytorch模型pth文件中读取参数成numpy矩阵的操作
2021/03/04 Python
AmazeUI 面板的实现示例
2020/08/17 HTML / CSS
加拿大户外探险购物网站:SAIL
2020/06/27 全球购物
八项规定整改措施
2014/02/12 职场文书
法人授权委托书范本
2014/09/17 职场文书
推广普通话共筑中国梦演讲稿
2014/09/21 职场文书
蓬莱阁导游词
2015/02/04 职场文书
货款欠条范本
2015/07/03 职场文书
合理缓解职场压力,让你随时保持最佳状态!
2019/06/21 职场文书
Sql Server 行数据的某列值想作为字段列显示的方法
2022/04/20 SQL Server
ubuntu20.04虚拟机无法上网的问题及解决
2022/12/24 Servers