当大家的站点越来越来越多的时候会发现管理起来也挺复杂的,所以这篇文章给大家分享下利用python批量检查网站的可用性的功能,对大家管理网站具有很实用的价值,有需要的朋友可以参考借鉴。
">
前言
随着站点的增多,管理复杂性也上来了,俗话说:人多了不好带,我发现站点多了也不好管,因为这些站点里有重要的也有不重要的,重要核心的站点当然就管理的多一些,像一些万年都不出一次问题的,慢慢就被自己都淡忘了,冷不丁那天出个问题,还的手忙脚乱的去紧急处理,所以规范的去管理这些站点是很有必要的,今天我们就做第一步,不管大站小站,先统一把监控做起来,先不说业务情况,最起码那个站点不能访问了,要第一时间报出来,别等着业务方给你反馈,就显得我们不够专业了,那接下来我们看看如果用python实现多网站的可用性监控,脚本如下:
#!/usr/bin/env python import pickle, os, sys, logging from httplib import HTTPConnection, socket from smtplib import SMTP def email_alert(message, status): fromaddr = 'xxx@163.com' toaddrs = 'xxxx@qq.com' server = SMTP('smtp.163.com:25') server.starttls() server.login('xxxxx', 'xxxx') server.sendmail(fromaddr, toaddrs, 'Subject: %s\r\n%s' % (status, message)) server.quit() def get_site_status(url): response = get_response(url) try: if getattr(response, 'status') == 200: return 'up' except AttributeError: pass return 'down' def get_response(url): try: conn = HTTPConnection(url) conn.request('HEAD', '/') return conn.getresponse() except socket.error: return None except: logging.error('Bad URL:', url) exit(1) def get_headers(url): response = get_response(url) try: return getattr(response, 'getheaders')() except AttributeError: return 'Headers unavailable' def compare_site_status(prev_results): def is_status_changed(url): status = get_site_status(url) friendly_status = '%s is %s' % (url, status) print friendly_status if url in prev_results and prev_results[url] != status: logging.warning(status) email_alert(str(get_headers(url)), friendly_status) prev_results[url] = status return is_status_changed def is_internet_reachable(): if get_site_status('www.baidu.com') == 'down' and get_site_status('www.sohu.com') == 'down': return False return True def load_old_results(file_path): pickledata = {} if os.path.isfile(file_path): picklefile = open(file_path, 'rb') pickledata = pickle.load(picklefile) picklefile.close() return pickledata def store_results(file_path, data): output = open(file_path, 'wb') pickle.dump(data, output) output.close() def main(urls): logging.basicConfig(level=logging.WARNING, filename='checksites.log', format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') pickle_file = 'data.pkl' pickledata = load_old_results(pickle_file) print pickledata if is_internet_reachable(): status_checker = compare_site_status(pickledata) map(status_checker, urls) else: logging.error('Either the world ended or we are not connected to the net.') store_results(pickle_file, pickledata) if __name__ == '__main__': main(sys.argv[1:])
脚本核心点解释:
1、getattr()是python的内置函数,接收一个对象,可以根据对象属性返回对象的值。
2、compare_site_status()函数是返回的是一个内部定义的函数。
3、map() ,需要2个参数,一个是函数,一个是序列,功能就是将序列中的每个元素应用函数方法。
总结
以上就是这篇文章的全部内容,有需要的朋友们可以参考借鉴。
以上是利用python批量检查网站的可用性的详细内容。更多信息请关注PHP中文网其他相关文章!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3汉化版
中文版,非常好用

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。