1. 程式人生 > >python--DenyHttp項目(2)--ACM監考客戶端測試版(1階段完成總結)

python--DenyHttp項目(2)--ACM監考客戶端測試版(1階段完成總結)

tdi text class 測試版 window etl operate comm decode

  客戶端:

‘‘‘
DenyManager.py
調用客戶端與客戶端界面
‘‘‘
from DenyClient import *
from DenyGui import *

if __name__ == __main__:
    clientConncet = DenyHttpClient()
    clientGui = DenyHttpGui()     
#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)
        if self.getdata == 1:
            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))
        if self.getdata == 0 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(rD:\DenyHttp\restore)    
    
    hostsName = C:\Windows\System32\drivers\etc\hosts
    filename = rD:\DenyHttp\hosts
    if os.path.exists(rD:\DenyHttp\hosts) and os.path.exists(rD:\DenyHttp\restore\hosts):
        print(filename + 已存在!)
    else:
        print(文件不存在,準備復制:)
        if not os.system(rcopy + hostsName + D:\DenyHttp):
            print(file remove from  + hostsName +  to  + filename)
        if not os.system(rcopy + 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(rcopy D:\DenyHttp\hosts C:\Windows\System32\drivers\etc):
        print(file hosts has been already discovered!)
‘‘‘恢復Hosts文件‘‘‘    
def Recoverfile():
    if not os.system(rcopy 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 0
        return str(%02d % self.hour) + : + str(%02d % self.minute) + : + str(%02d % self.sec)
        

 

python--DenyHttp項目(2)--ACM監考客戶端測試版(1階段完成總結)