客户端:
1.既然脚本是让别人用的,怎么说也得有个界面,(虽然很low)
''' DenyManager.py 调用客户端与客户端界面 ''' from DenyClient import * from DenyGui import * if __name__ == '__main__': clientConncet = DenyHttpClient() clientGui = DenyHttpGui()
2.客户端的界面很简单,签到还没写,(构思中...)其实能用的就一个比赛开始的Button
这是后台跑的数据
这个连接服务器的messageBox为了改变比赛开始Button的状态为不可点击
检查版本信息,在确定开始比赛之前检查版本信息,版本不对,更新吧(下个新版的就好了)
之后,开始比赛!
#coding=utf-8 ''' DenyGui.py 客户端的界面 1.倒计时lable 2.签到Button(未实现) 3.开始比赛Button ''' import tkinter as tk import random import time import datetime import sys import os ''' 用messagebox没有下面这句,报错''' from tkinter import messagebox#专门加上 from DenyClient import * from CountTime import * from tkinter.constants import * import threading class DenyHttpGui(object): def __init__(self): '''创建一个实例对象,进行倒计时''' self.changetime = ChangeTime() '''定义窗口''' self.root = tk.Tk() '''标题''' self.root.title('404监考系统') '''大小''' self.curWidth = 300 self.curHeight = 100 '''位置''' scnWidth,scnHeight = self.root.maxsize() tmpcnf = '%dx%d+%d+%d'%(self.curWidth,self.curHeight, (scnWidth-self.curWidth)/2,(scnHeight-self.curHeight)/2) self.root.geometry(tmpcnf) self.root.resizable(False, False) '''倒计时Frame''' self.frameTop = tk.Frame(self.root,height=45,width=300) '''Button Frame''' self.frameBottom = tk.Frame(self.root,height=55,width=300) '''把Button顶上去''' self.frameDemo = tk.Frame(self.root,height=10) self.frameTop.pack(side=tk.TOP) self.frameBottom.pack(side=tk.TOP) self.frameDemo.pack(side=tk.TOP) '''定义倒计时属性''' self.decTimeLable = tk.Label(self.frameTop,text='正在连接服务器...',font=("Arial",20)) self.decTimeLable.pack(side=tk.TOP) '''定义签到Button''' tk.Button(self.frameBottom, text='签到', height=1,width=8,padx=8,pady=8, font=("Arial",14), command=self.check).pack(side=tk.LEFT) '''定义比赛Button''' self.BEGIN = tk.Button(self.frameBottom, text='比赛开始', height=1,width=8,padx=8,pady=8, font=("Arial",14), command=self.startButton) self.BEGIN.pack(side=tk.RIGHT) self.decTimeLable.pack() self.root.mainloop() '''开始比赛,启动客户端服务''' def startButton(self): self.BEGIN.config(state='disable') denyhttpclinet = DenyHttpClient() threadQueryTime = threading.Thread(target=denyhttpclinet.queryTime) threadQueryTime.start() '''下面这句,为了刷新Button状态为不可点击状态''' tk.messagebox.showwarning('警告', '正在连接服务器...') threadQueryTime.join() '''进行版本更新''' '''线程之间用returnval传递值''' if denyhttpclinet.returnval == 1: self.decTimeLable.configure(text='正在检查版本信息...') threadCheckTime = threading.Thread(target=denyhttpclinet.checkVersion) threadCheckTime.start() threadCheckTime.join() print(denyhttpclinet.versionRight) if denyhttpclinet.versionRight == 1: self.decTimeLable.configure(text='00:00:00') tk.messagebox.showwarning('警告', '当前为最新版本!') else: tk.messagebox.showwarning('警告', '版本更新!\n请联系管理员') sys.exit() threadContest = threading.Thread(target=denyhttpclinet.startContest) threadContest.start() elif denyhttpclinet.returnval == 0: self.decTimeLable.configure(text='比赛尚未开始!') elif denyhttpclinet.returnval == -2: self.decTimeLable.configure(text='比赛已经开始!') else: self.decTimeLable.configure(text='比赛已结束!') if denyhttpclinet.endTime !='' and denyhttpclinet.now != '': self.totaltime = (denyhttpclinet.endTime - datetime.datetime.strptime(denyhttpclinet.now, "%Y-%m-%d %H:%M:%S")).seconds self.changetime = ChangeTime(self.totaltime) threadDecTime = threading.Thread(target=self.textadd()) threadDecTime.start() '''改变Button状态''' def buttonNormal(self,sleepTime): while self.mark: if self.mark : self.BEGIN.config(state='normal') time.sleep(1) def check(self): tk.messagebox.showwarning('警告', '待更新') '''刷新倒计时''' def textadd(self): t = self.changetime.subTime() if t == '00:00:00': self.BEGIN.config(state='normal') self.decTimeLable.configure(text='比赛结束!')#这个修改lable值 return self.decTimeLable.configure(text='距比赛结束: '+t) self.decTimeLable.after(1000, self.textadd) if __name__=='__main__': Demo = DenyHttpGui() Demo.startGui()
#coding:gbk ''' DenyClient.py 客户端与服务器端的操作 1.连接服务器 2.监听端口 3.查询比赛时间 4.监听本地网络连接状态 5.违规报警 ''' from socket import * import time import datetime from ClientOperate import * import threading import subprocess import multiprocessing class DenyHttpClient(): def __init__(self): '''服务器套接字''' self.HOST = '10.251.234.141' self.PORT = 1122 self.ADDR = (self.HOST, self.PORT) '''数据包大小''' self.BUFSIZE = 1024 self.now = '' '''比赛结束时间''' self.endTime = '' '''线程之间传值''' self.returnval = 0 '''版本号''' self.versionRight = 0 '''检查版本''' def checkVersion(self): msg = 'V:0' self.listener(msg) ': self.versionRight = 1 elif self.getdata == '-1': self.versionRight = -1 '''查询比赛时间,确认连接''' def queryTime(self): if os.system('ping ' + self.HOST): print('无法连接到目标主机!') return self.now = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S") msg = 'B:' + str(self.now) try: if self.listener(msg): msg = 'IP:' + gethostbyname(gethostname()) self.listener(msg) self.returnval = 1 return 1 elif self.getdata == '-1': print('比赛已结束') self.returnval = -1 return -1 elif self.getdata == '-2': self.returnval = -2 print('比赛已经开始') return -2 else: self.returnval = 0 return 0 except ConnectionRefusedError: self.returnval = 0 return 0 except TimeoutError: self.returnval = 0 return 0 '''开始检测与本地监听''' def startContest(self): self.t1 = threading.Thread(target=self.contestBegin)#参数是函数对象 self.t2 = threading.Thread(target=self.contestEnd) self.t1.setDaemon(True) self.t2.setDaemon(True) self.t1.start() self.t2.start() self.t1.join() self.t2.join() return 0 '''监听端口信息''' def listener(self,data): self.client = socket(AF_INET,SOCK_STREAM) self.client.connect(self.ADDR) self.client.send(data.encode('utf-8')) print('发送消息给%s: %s' % (self.HOST, data)) self.getdata = self.client.recv(self.BUFSIZE) self.getdata = self.getdata.decode('utf-8') print('接受的消息 %s' % (self.getdata)) ' or self.getdata == '-1': return False elif len(self.getdata) > 2: self.endTime = datetime.datetime.strptime(self.getdata, "%Y-%m-%d %H:%M:%S") return True ''' 在比赛过程中 1.执行拒绝HTTP操作 2.不断检测网络是否联通 ''' def contestBegin(self): Denyfile() if not detectnet(): print('success deny http!') else: print('failed deny http!') return self.begin = 1 while self.begin: if detectnet(): print('somebody cheating!') self.listener('Error: ' + gethostbyname(gethostname())) time.sleep(5) '''检查是否到比赛时间,每隔 剩余时间二分之一检查一次,比赛结束后,恢复网络''' def contestEnd(self): print('检测比赛结束.......') while True: if self.endTime > datetime.datetime.now(): sleepTime = (self.endTime - datetime.datetime.now()).seconds // 2 if not sleepTime > 5: sleepTime = 2 time.sleep(sleepTime) print('contestEnd: 比赛进行中...') else: break self.begin = 0 print('contest end!') Recoverfile() if os.system('ping www.baidu.com') == 1: print('contest end but recover failed!!!') else: print('比赛完美举办!') if __name__ == '__main__': c = DenyHttpClient() c.checkVersion() # c.startContest()
''' ClientOperate.py 对文件的复制,恢复,修改处理 ''' #coding:gbk import os import sys from subprocess import * '''复制Hosts文件,添加禁止访问网址,备份''' def Denyfile(): if not os.path.exists('D:\DenyHttp'): os.mkdir('D:\DenyHttp') os.mkdir(r'D:\DenyHttp\restore') hostsName = 'C:\Windows\System32\drivers\etc\hosts' filename = r'D:\DenyHttp\hosts' if os.path.exists(r'D:\DenyHttp\hosts') and os.path.exists(r'D:\DenyHttp\restore\hosts'): print(filename + '已存在!') else: print('文件不存在,准备复制:') if not os.system(r'copy '+ hostsName +' D:\DenyHttp'): print('file remove from ' + hostsName + ' to ' + filename) if not os.system(r'copy '+ hostsName + r' D:\DenyHttp\restore'): print('file remove from ' + hostsName + ' to D:\DenyHttp\restore') L = [] denyNetAddress = getHTTPList(L) '''添加htttp到文件''' for s in denyNetAddress: os.system('echo ' + s +'>>' + filename) '''修改hosts文件''' if not os.system(r'copy D:\DenyHttp\hosts C:\Windows\System32\drivers\etc'): print('file hosts has been already discovered!') '''恢复Hosts文件''' def Recoverfile(): if not os.system(r'copy D:\DenyHttp\restore\hosts C:\Windows\System32\drivers\etc'): print('file hosts has been already recovered!') '''覆盖Hosts文件后,检查是否成功覆盖,成功后将不能访问特定网址''' def detectnet(): L = [] denyNetAddress = getNetList(L) mark = 1 for s in denyNetAddress: p = Popen(["ping.exe" , s], stdin=PIPE,stdout=PIPE,stderr=PIPE, shell=True) out = p.stdout.read() if '127.0.0.1' in str(out): mark = 0 '''mark为假不能访问''' if not mark: print('can\'t request http') else: print('can request http') return mark '''初始化目标网址列表''' def getHTTPList(denyNetAddress = []): denyNetAddress.append('127.0.0.1 www.baidu.com') denyNetAddress.append('127.0.0.1 www.sogou.com') denyNetAddress.append('127.0.0.1 sg.search.yahoo.com') denyNetAddress.append('127.0.0.1 cn.bing.com') denyNetAddress.append('127.0.0.1 www.soso.com') denyNetAddress.append('127.0.0.1 www.cnblogs.com') denyNetAddress.append('127.0.0.1 blog.csdn.net') return denyNetAddress def getNetList(denyNetAddress = []): denyNetAddress.append('www.baidu.com') denyNetAddress.append('www.sogou.com') denyNetAddress.append('sg.search.yahoo.com') denyNetAddress.append('cn.bing.com') denyNetAddress.append('www.soso.com') denyNetAddress.append('www.cnblogs.com') denyNetAddress.append('blog.csdn.net') return denyNetAddress if __name__ == '__main__': # Denyfile() Recoverfile() # print(detectnet())
#coding:utf-8 ''' CountTime.py 将秒转化为时间格式进行倒计时 ''' class ChangeTime(): def __init__(self,totaltime=0): self.sec = totaltime self.hour = int(self.sec / 3600) self.sec = self.sec % 3600 self.minute = int(self.sec / 60) self.sec = int(self.sec % 60) def subTime(self): if self.sec > 0: self.sec -= 1 else: if self.minute > 0: self.minute -= 1 self.sec = 59 else: if self.hour > 0: self.hour -= 1 self.minute = 59 self.sec = 59 else: ' return str('%02d' % self.hour) + ':' + str('%02d' % self.minute) + ':' + str('%02d' % self.sec)