一、利用python批量测试网站是否可正常被访问

应用场景:当有大量网站需要检测是否能正常打开时,可以采用此方式;

import requests #创建函数netcheck,传入参数为url,即需要被访问的网址 def netcheck(url): try: #利用reque访问url地址,timeout为超时参数,单位为秒;r.status_code为请求状态码 r = reque(url, timeout = 1) status_code = r.status_code return status_code except Exception as e: return e if __name__ == "__main__": #需要准备好都是url 的文件,每个url一行,打开一个txt文件,每次读入一行line with open("urlli;) as f: try: for line in f: #strip() 移除字符串开头和结尾的空格和换行符 status = netcheck()) if status == 200: print() + ': successful') #打开一个txt文件,以追加的方式(a),将请求状态码为200的url写入到一个文档中 with open('valid_;, 'a') as f1: (line) else: #打开另一个txt文件,以追加的方式(a),将请求状态码为不是200的url写入到一个文档中 print()+': unsuccessful') with open('invalid_;, 'a') as f2: (line) except Exception as e: print (e)

不足之处:对于网站中子模块是否能正常访问,并不能检测到;

他山之石:利用【Xenu】这个软件,可以对一个网站中所有的连接进行尝试访问,并给出结果。

二、利用python批量获得linux系统时间

应用场景:当有一批服务器时,需要查看各个服务器上的系统时间;

#-*- coding: utf-8 -*- import paramiko import threading import time def ssh2(ip,username,passwd,cmd): try: ssh = () #创建ssh对象 #允许连接不在know_hosts文件中的主机 ()) (ip,'22',username,passwd,timeout=5) for m in cmd: #exec_command 执行命令并获取命令结果. #stdin为输入的命令,stdout为命令返回的结果,stderr为命令错误时返回的结果 stdin, stdout, stderr = (m) #("Y") #简单交互,输入 ‘Y’ out = () if (m=='date'): #out是个list,转成str,"".join(out) result1 = ip+ "=="+"".join(out) #print (result1) with open(';,'a') as f1: (result1) else: #获得当前时间,并转成时间戳 current_timestampe = in()) os_timestampe = int("".join(out)) #当前时间和系统时间差5秒,则输出服务器IP和服务器时间和当前时间 if (current_timestampe-os_timestampe) >5: os_time = (os_timestampe) os_time_time = ("%Y--%m--%d %H:%M:%S", os_time) current_time = (current_timestampe) current_time_time = ("%Y--%m--%d %H:%M:%S", current_time) result2 = "current_time=="+current_time_time+"==="+ip+ "==server-time==" + os_time_time+'\n' print(result2) with open(';,'a') as f2: (result2) () except : print ()) print ()) print ('%s\tError\n'%(ip)) if __name__=='__main__': # cmd 你要执行的命令列表;在linux中date +%s返回时间戳,单位为秒 cmd = ['date','date +%s']#你要执行的命令列表 # 读取存储ip、用户名、密码的文件,循环执行 with open("i;) as f: lines = f.readlines() for i in range(len(lines)): cols = lines[i].split() ip = cols[0] passwd = cols[1] username='root' #单线程 ssh2(ip,username,passwd,cmd) #threads = [] #多线程 #a=(target=ssh2,args=(ip,username,passwd,cmd)) #a.start()

扩展应用:可以执行date命令,那也可以执行其他命令,比如内存,存储,性能等

1.《如何批量打开一个网址,如何批量打开图片?》援引自互联网,旨在传递更多网络信息知识,仅代表作者本人观点,与本网站无关,侵删请联系页脚下方联系方式。

2.《如何批量打开一个网址,如何批量打开图片?》仅供读者参考,本网站未对该内容进行证实,对其原创性、真实性、完整性、及时性不作任何保证。

3.文章转载时请保留本站内容来源地址,https://www.lu-xu.com/keji/3217610.html