Форум сайта python.su
SingularityНа детском компе у меня программа стоит ,которая закрывает браузер с сайтами где встречаются слова секс порно и тд, думал такое на питоне написать
У меня тетей Adblock режет, если сам не погуглю на порно никак не попаду.
Отредактировано sanodin (Апрель 28, 2013 19:36:36)
Офлайн
Примерно так , на основе сниффера, только на некоторых сайтах кодировка дает сбой,надо доработать
и вместо закрытия браузера , может посылать пакет с флагом rts на закрытие соединения? я правда пока не вкурил запросы
# coding: cp1251 from socket import * import struct import sys import re import subprocess import urllib2 # receive a datagram def receiveData(s): data = '' try: data = s.recvfrom(65565) except timeout: data = '' except: print "An error happened: " sys.exc_info() return data[0] # get Type of Service: 8 bits def getTOS(data): precedence = {0: "Routine", 1: "Priority", 2: "Immediate", 3: "Flash", 4: "Flash override", 5: "CRITIC/ECP", 6: "Internetwork control", 7: "Network control"} delay = {0: "Normal delay", 1: "Low delay"} throughput = {0: "Normal throughput", 1: "High throughput"} reliability = {0: "Normal reliability", 1: "High reliability"} cost = {0: "Normal monetary cost", 1: "Minimize monetary cost"} # get the 3rd bit and shift right D = data & 0x10 D >>= 4 # get the 4th bit and shift right T = data & 0x8 T >>= 3 # get the 5th bit and shift right R = data & 0x4 R >>= 2 # get the 6th bit and shift right M = data & 0x2 M >>= 1 # the 7th bit is empty and shouldn't be analyzed tabs = '\n\t\t\t' TOS = precedence[data >> 5] + tabs + delay[D] + tabs + throughput[T] + tabs + \ reliability[R] + tabs + cost[M] return TOS # get Flags: 3 bits def getFlags(data): flagR = {0: "0 - Reserved bit"} flagDF = {0: "0 - Fragment if necessary", 1: "1 - Do not fragment"} flagMF = {0: "0 - Last fragment", 1: "1 - More fragments"} # get the 1st bit and shift right R = data & 0x8000 R >>= 15 # get the 2nd bit and shift right DF = data & 0x4000 DF >>= 14 # get the 3rd bit and shift right MF = data & 0x2000 MF >>= 13 tabs = '\n\t\t\t' flags = flagR[R] + tabs + flagDF[DF] + tabs + flagMF[MF] return flags # get protocol: 8 bits def getProtocol(protocolNr): protocolFile = open('Protocol.txt', 'r') protocolData = protocolFile.read() protocol = re.findall(r'\n' + str(protocolNr) + ' (?:.)+\n', protocolData) if protocol: protocol = protocol[0] protocol = protocol.replace("\n", "") protocol = protocol.replace(str(protocolNr), "") protocol = protocol.lstrip() return protocol else: return 'No such protocol.' while True: # the public network interface HOST = gethostbyname(gethostname()) # create a raw socket and bind it to the public interface s = socket(AF_INET, SOCK_RAW, IPPROTO_IP) s.bind((HOST, 0)) # Include IP headers s.setsockopt(IPPROTO_IP, IP_HDRINCL, 1) s.ioctl(SIO_RCVALL, RCVALL_ON) data = receiveData(s) # get the IP header (the first 20 bytes) and unpack them # B - unsigned char (1) # H - unsigned short (2) # s - string unpackedData = struct.unpack('!BBHHHBBH4s4s' , data[:20]) version_IHL = unpackedData[0] version = version_IHL >> 4 # version of the IP IHL = version_IHL & 0xF # internet header length TOS = unpackedData[1] # type of service totalLength = unpackedData[2] ID = unpackedData[3] # identification flags = unpackedData[4] fragmentOffset = unpackedData[4] & 0x1FFF TTL = unpackedData[5] # time to live protocolNr = unpackedData[6] checksum = unpackedData[7] sourceAddress = inet_ntoa(unpackedData[8]) destinationAddress = inet_ntoa(unpackedData[9]) #print "An IP packet with the size %i was captured." % (unpackedData[2]) dic=['sex','porno','секс','порно','трах'] f=data.split() e=0 for i in f: e+=1 if i == 'Host:': print f[e] url=f[e] try: c=urllib2.urlopen('http://'+url) contents=c.read( ) for i in re.split("[.+!<>:;,=() ]",contents): #print i if i in dic: print '-------------------------------------------',i subprocess.Popen('TASKKILL /F /IM iron.exe' , shell = True) break except: print 'err' s.ioctl(SIO_RCVALL, RCVALL_OFF)
Отредактировано sanodin (Апрель 27, 2013 20:39:05)
Офлайн
Переписал
# -*- coding: utf8 -*- from grab import Grab import threading from socket import * import struct import sys import re import subprocess import urllib2 import traceback # receive a datagram def receiveData(s): data = '' try: data = s.recvfrom(65565) except timeout: data = '' except: print ("An error happened: ") sys.exc_info() return data[0] # get Type of Service: 8 bits def getTOS(data): precedence = {0: "Routine", 1: "Priority", 2: "Immediate", 3: "Flash", 4: "Flash override", 5: "CRITIC/ECP", 6: "Internetwork control", 7: "Network control"} delay = {0: "Normal delay", 1: "Low delay"} throughput = {0: "Normal throughput", 1: "High throughput"} reliability = {0: "Normal reliability", 1: "High reliability"} cost = {0: "Normal monetary cost", 1: "Minimize monetary cost"} # get the 3rd bit and shift right D = data & 0x10 D >>= 4 # get the 4th bit and shift right T = data & 0x8 T >>= 3 # get the 5th bit and shift right R = data & 0x4 R >>= 2 # get the 6th bit and shift right M = data & 0x2 M >>= 1 # the 7th bit is empty and shouldn't be analyzed tabs = '\n\t\t\t' TOS = precedence[data >> 5] + tabs + delay[D] + tabs + throughput[T] + tabs + \ reliability[R] + tabs + cost[M] return TOS # get Flags: 3 bits def getFlags(data): flagR = {0: "0 - Reserved bit"} flagDF = {0: "0 - Fragment if necessary", 1: "1 - Do not fragment"} flagMF = {0: "0 - Last fragment", 1: "1 - More fragments"} # get the 1st bit and shift right R = data & 0x8000 R >>= 15 # get the 2nd bit and shift right DF = data & 0x4000 DF >>= 14 # get the 3rd bit and shift right MF = data & 0x2000 MF >>= 13 tabs = '\n\t\t\t' flags = flagR[R] + tabs + flagDF[DF] + tabs + flagMF[MF] return flags # get protocol: 8 bits def getProtocol(protocolNr): protocolFile = open('Protocol.txt', 'r') protocolData = protocolFile.read() protocol = re.findall(r'\n' + str(protocolNr) + ' (?:.)+\n', protocolData) if protocol: protocol = protocol[0] protocol = protocol.replace("\n", "") protocol = protocol.replace(str(protocolNr), "") protocol = protocol.lstrip() return protocol else: return 'No such protocol.' while True: def get_tb(): tmp=traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2],) return ''.join(tmp) # the public network interface HOST = gethostbyname(gethostname()) # create a raw socket and bind it to the public interface s = socket(AF_INET, SOCK_RAW, IPPROTO_IP) s.bind((HOST, 0)) # Include IP headers s.setsockopt(IPPROTO_IP, IP_HDRINCL, 1) s.ioctl(SIO_RCVALL, RCVALL_ON) data = receiveData(s) # get the IP header (the first 20 bytes) and unpack them # B - unsigned char (1) # H - unsigned short (2) # s - string unpackedData = struct.unpack('!BBHHHBBH4s4s' , data[:20]) version_IHL = unpackedData[0] version = version_IHL >> 4 # version of the IP IHL = version_IHL & 0xF # internet header length TOS = unpackedData[1] # type of service totalLength = unpackedData[2] ID = unpackedData[3] # identification flags = unpackedData[4] fragmentOffset = unpackedData[4] & 0x1FFF TTL = unpackedData[5] # time to live protocolNr = unpackedData[6] checksum = unpackedData[7] sourceAddress = inet_ntoa(unpackedData[8]) destinationAddress = inet_ntoa(unpackedData[9]) f=data.split() e=0 for i in f: e+=1 if i == 'Referer:': print ' ',f[e],' ' url=f[e] try: g = Grab() g.go(url) r = g.search(u'sex') #r1=g.search(u'sex'.encode('cp1251'), byte=True) s = g.search(u'секс') #s1=g.search(u'секс'.encode('cp1251'), byte=True) q = g.search(u'порно') #q1=g.search(u'порно'.encode('cp1251'), byte=True) w = g.search(u'трах') #w1=g.search(u'трах'.encode('cp1251'), byte=True) print s sp=[s,q,w,r] for i in sp: if i == True: #print 'у данного сайта тематика-',i subprocess.Popen('TASKKILL /F /IM iron.exe' , shell = True) #subprocess.Popen('TASKKILL /F /IM Chrome.exe' , shell = True) #subprocess.Popen('TASKKILL /F /IM iexplore.exe' , shell = True) #subprocess.Popen('TASKKILL /F /IM firefox.exe' , shell = True) except: print get_tb()
Отредактировано sanodin (Апрель 28, 2013 14:43:24)
Офлайн
Или такой вариант
# -*- coding: cp1251 -*- from grab import Grab import threading from socket import * import struct import sys import re import subprocess import urllib2 import traceback # receive a datagram def receiveData(s): data = '' try: data = s.recvfrom(65565) except timeout: data = '' except: print ("An error happened: ") sys.exc_info() return data[0] # get Type of Service: 8 bits def getTOS(data): precedence = {0: "Routine", 1: "Priority", 2: "Immediate", 3: "Flash", 4: "Flash override", 5: "CRITIC/ECP", 6: "Internetwork control", 7: "Network control"} delay = {0: "Normal delay", 1: "Low delay"} throughput = {0: "Normal throughput", 1: "High throughput"} reliability = {0: "Normal reliability", 1: "High reliability"} cost = {0: "Normal monetary cost", 1: "Minimize monetary cost"} # get the 3rd bit and shift right D = data & 0x10 D >>= 4 # get the 4th bit and shift right T = data & 0x8 T >>= 3 # get the 5th bit and shift right R = data & 0x4 R >>= 2 # get the 6th bit and shift right M = data & 0x2 M >>= 1 # the 7th bit is empty and shouldn't be analyzed tabs = '\n\t\t\t' TOS = precedence[data >> 5] + tabs + delay[D] + tabs + throughput[T] + tabs + \ reliability[R] + tabs + cost[M] return TOS # get Flags: 3 bits def getFlags(data): flagR = {0: "0 - Reserved bit"} flagDF = {0: "0 - Fragment if necessary", 1: "1 - Do not fragment"} flagMF = {0: "0 - Last fragment", 1: "1 - More fragments"} # get the 1st bit and shift right R = data & 0x8000 R >>= 15 # get the 2nd bit and shift right DF = data & 0x4000 DF >>= 14 # get the 3rd bit and shift right MF = data & 0x2000 MF >>= 13 tabs = '\n\t\t\t' flags = flagR[R] + tabs + flagDF[DF] + tabs + flagMF[MF] return flags # get protocol: 8 bits def getProtocol(protocolNr): protocolFile = open('Protocol.txt', 'r') protocolData = protocolFile.read() protocol = re.findall(r'\n' + str(protocolNr) + ' (?:.)+\n', protocolData) if protocol: protocol = protocol[0] protocol = protocol.replace("\n", "") protocol = protocol.replace(str(protocolNr), "") protocol = protocol.lstrip() return protocol else: return 'No such protocol.' while True: def get_tb(): tmp=traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2],) return ''.join(tmp) # the public network interface HOST = gethostbyname(gethostname()) # create a raw socket and bind it to the public interface s = socket(AF_INET, SOCK_RAW, IPPROTO_IP) s.bind((HOST, 0)) # Include IP headers s.setsockopt(IPPROTO_IP, IP_HDRINCL, 1) s.ioctl(SIO_RCVALL, RCVALL_ON) data = receiveData(s) # get the IP header (the first 20 bytes) and unpack them # B - unsigned char (1) # H - unsigned short (2) # s - string unpackedData = struct.unpack('!BBHHHBBH4s4s' , data[:20]) version_IHL = unpackedData[0] version = version_IHL >> 4 # version of the IP IHL = version_IHL & 0xF # internet header length TOS = unpackedData[1] # type of service totalLength = unpackedData[2] ID = unpackedData[3] # identification flags = unpackedData[4] fragmentOffset = unpackedData[4] & 0x1FFF TTL = unpackedData[5] # time to live protocolNr = unpackedData[6] checksum = unpackedData[7] sourceAddress = inet_ntoa(unpackedData[8]) destinationAddress = inet_ntoa(unpackedData[9]) f=data.split() dic=['sex','Sex','Porno','porno',"секс","порно","дойки","трах","сиськи",'Секс','Порно'] e=0 for i in f: e+=1 if i == 'Referer:': print f[e] url=f[e] try: g = Grab() g.go(url) s=g.rex_text('<title>([^>]+)</title>') for i in s.split(' '): t=i.encode('cp1251') print t if t in dic: #print 'у данного сайта тематика-',i subprocess.Popen('TASKKILL /F /IM iron.exe' , shell = True) #subprocess.Popen('TASKKILL /F /IM Chrome.exe' , shell = True) #subprocess.Popen('TASKKILL /F /IM iexplore.exe' , shell = True) #subprocess.Popen('TASKKILL /F /IM firefox.exe' , shell = True) except: print get_tb()
Отредактировано sanodin (Апрель 28, 2013 14:44:34)
Офлайн
Если возможно, попрошу Вас программисты , оптимизировать данный код
Офлайн
Попробуйте http://dns.yandex.ru/
77.88.8.7
фильтрация опасных сайтов и сайтов для взрослых
Офлайн
pmusТоже вариант
Попробуйте http://dns.yandex.ru/77.88.8.7фильтрация опасных сайтов и сайтов для взрослых
Офлайн
sanodin
ваш код это стрельба межконтинетальной ракетой по крохотному дому фермера:-)
Например, сидит ребенок честно ищет полезную информацию. Находит сайт который открывает еще вкладку с порно страницей. Ребеныш этого не хотел, просто есть дерьмо-сайты. И вот у него хлопается браузер с кучкой других полезных вкладок. Печальны глаза ребенка.
Если где то не прав - поправьте.
Офлайн
JOHN_168-)
sanodinваш код это стрельба межконтинетальной ракетой по крохотному дому фермера:-)Например, сидит ребенок честно ищет полезную информацию. Находит сайт который открывает еще вкладку с порно страницей. Ребеныш этого не хотел, просто есть дерьмо-сайты. И вот у него хлопается браузер с кучкой других полезных вкладок. Печальны глаза ребенка.Если где то не прав - поправьте.
Отредактировано sanodin (Апрель 30, 2013 06:49:54)
Офлайн