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中Flask框架简单入门实例
Mar 21 Python
Python在Windows和在Linux下调用动态链接库的教程
Aug 18 Python
python实现将内容分行输出
Nov 05 Python
python监控linux内存并写入mongodb(推荐)
Sep 11 Python
Python RabbitMQ消息队列实现rpc
May 30 Python
老生常谈python中的重载
Nov 11 Python
浅谈python3中input输入的使用
Aug 02 Python
python选取特定列 pandas iloc,loc,icol的使用详解(列切片及行切片)
Aug 06 Python
python中enumerate() 与zip()函数的使用比较实例分析
Sep 03 Python
python3 sleep 延时秒 毫秒实例
May 04 Python
python logging模块的使用
Sep 07 Python
Python全局变量与global关键字常见错误解决方案
Oct 05 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提示Warning:mysql_fetch_array() expects的解决方法
2014/12/16 PHP
php结合web uploader插件实现分片上传文件
2016/05/10 PHP
PHP简单字符串过滤方法示例
2016/09/04 PHP
PHP 多进程与信号中断实现多任务常驻内存管理实例方法
2019/10/04 PHP
Js 本页面传值实现代码
2009/05/17 Javascript
分享一个自己动手写的jQuery分页插件
2014/08/28 Javascript
谈谈PHP中相对路径的问题与绝对路径的使用
2016/08/16 Javascript
基于JS实现bookstore静态页面的实例代码
2017/02/22 Javascript
Bootstrap入门教程一Hello Bootstrap初识
2017/03/02 Javascript
Vue.js组件间的循环引用方法示例
2017/12/27 Javascript
详解原生JS回到顶部
2019/03/25 Javascript
微信小程序实现电影App导航和轮播
2020/11/30 Javascript
[04:53]DOTA2英雄基础教程 祈求者
2014/01/03 DOTA
[02:33]2014DOTA2 TI每日综述 LGD涉险晋级DK闯入胜者组
2014/07/14 DOTA
Python基本数据类型详细介绍
2014/03/11 Python
Python中使用copy模块实现列表(list)拷贝
2015/04/14 Python
python实现在每个独立进程中运行一个函数的方法
2015/04/23 Python
Python求两个文本文件以行为单位的交集、并集与差集的方法
2015/06/17 Python
浅谈django model的get和filter方法的区别(必看篇)
2017/05/23 Python
Python 查看文件的编码格式方法
2017/12/21 Python
Python实现求数列和的方法示例
2018/01/12 Python
python实现小球弹跳效果
2019/05/10 Python
python 命名规范知识点汇总
2020/02/14 Python
python读取mysql数据绘制条形图
2020/03/25 Python
pycharm 对代码做静态检查操作
2020/06/09 Python
CSS3中的元素过渡属性transition示例详解
2016/11/30 HTML / CSS
解决CSS3 transition-delay 属性默认值0不带单位失效的问题
2020/10/29 HTML / CSS
美国汽配连锁巨头Pep Boys官网:轮胎更换、汽车维修服务和汽车零部件
2017/01/14 全球购物
什么是SCM(软件配置管理)
2014/08/16 面试题
Unix里面如何在后台运行程序
2016/10/14 面试题
急诊科护士自我鉴定
2013/10/14 职场文书
小学教师师德反思
2014/02/03 职场文书
楼面经理岗位职责范本
2014/02/18 职场文书
学校2014年度工作总结
2014/12/06 职场文书
师德师风事迹材料
2014/12/20 职场文书
高三复习计划
2015/01/19 职场文书