def get_shop_info(self): #接收商店信息 self.ShopList.clear() s=socket(AF_INET,SOCK_DGRAM) timeout = ip.TIMEOUT s.settimeout(timeout) info={} info["request"]="shopinfo" info["timestamp"]=ip.get_time_stamp() info = json.dumps(info) res=ip.encrypt(info)#encrypt s.sendto(res,(ip.HOST,ip.PORT)) data,ADDR = s.recvfrom(ip.BUFFERSIZE) data=ip.decrypt(data) shop_dic=eval(data) self.shop_id=[] shop_num=len(shop_dic) for i in range(shop_num): string="Shop Name: "+shop_dic[str(i)]["shopname"]+"\n"+"Owner ID: "+shop_dic[str(i)]["id"]+"\n"+"Owner name: "+shop_dic[str(i)]["ownername"]+'\n' item=QListWidgetItem() item.setIcon(QtGui.QIcon('icon/shop.ico')) item.setText(string) self.shop_id.append(int(shop_dic[str(i)]["id"])) self.ShopList.insertItem(i,item) s.close()
def send_or_broadcast_message(self): user_id=self.UserMessageLine.text() text=self.textEdit.toPlainText() self.textEdit.clear() s=socket(AF_INET,SOCK_DGRAM) timeout = ip.TIMEOUT s.settimeout(timeout) info={} if user_id == "": #为空,要广播 info["request"]="broadcast" info["content"]=text info["timestamp"]=ip.get_time_stamp() else: info["request"]="inform" info["user_id"]=user_id info["content"]=text info["timestamp"]=ip.get_time_stamp() info = json.dumps(info) res=ip.encrypt(info)#encrypt s.sendto(res,(ip.HOST,ip.PORT)) data,ADDR = s.recvfrom(ip.BUFFERSIZE) data=ip.decrypt(data) data=eval(data) if data["state"]=="fail": self.act_fail.emit() elif data["state"]=="succeed": self.UserMessageLine.clear() s.close()
def send_message(self): #发送登录信息 ID=self.IDLine.text() PassWord=self.PasswordLine.text() addr=(ip.HOST,ip.PORT) s=socket(AF_INET,SOCK_DGRAM) timeout = ip.TIMEOUT s.settimeout(timeout) info={} info["request"]="login" info["id"]=ID info["password"]=PassWord info["timestamp"]=ip.get_time_stamp() info = json.dumps(info) res=ip.encrypt(info)#encrypt self.PasswordLine.setText("") s.sendto(res,(ip.HOST,ip.PORT)) data,ADDR = s.recvfrom(ip.BUFFERSIZE) data=ip.decrypt(data) res=eval(data) #接收服务器发来的信息,传递相应信息 if res["state"]=="fail": self.login_fail.emit() if res["state"]=="succeed": self.clear() self.hide() emit_dic={} emit_dic["id"]=res["id"] emit_dic["name"]=res["name"] if res["authority"] == "user": self.login_succeed_user.emit(emit_dic) elif res["authority"] == "admin": self.login_succeed_admin.emit(emit_dic) s.close()
def search_goods(self): #获取当前商店的商品信息 self.listWidget.clear() s=socket(AF_INET,SOCK_DGRAM) timeout = ip.TIMEOUT s.settimeout(timeout) info={} info["request"]="getgoods" info["shop_id"]=str(self.shop_id) info["timestamp"]=ip.get_time_stamp() info = json.dumps(info) res=ip.encrypt(info)#encrypt s.sendto(res,(ip.HOST,ip.PORT)) data,ADDR = s.recvfrom(ip.BUFFERSIZE) data=ip.decrypt(data) goods_dic=eval(data) self.goods_id={} self.goods_name={} self.goods_price={} goods_num=len(goods_dic) for i in range(goods_num): if str(goods_dic[str(i)]["num"])!='0': string="Good Name: "+goods_dic[str(i)]["good_name"]+"\n"+"Good ID: "+goods_dic[str(i)]["good_id"]+"\n"+"Good Price: "+goods_dic[str(i)]["price"]+"\n"+"Num Left: "+str(goods_dic[str(i)]["num"]) item=QListWidgetItem() item.setIcon(QtGui.QIcon('icon/list.ico')) item.setText(string) self.goods_id[i]=(int(goods_dic[str(i)]["good_id"])) self.goods_name[i]=goods_dic[str(i)]["good_name"] ss=goods_dic[str(i)]["price"] ss=ss.replace("$","") self.goods_price[i]=float(ss) self.listWidget.insertItem(i,item) s.close()
def good_item_clicked(self,item): #用户点击商品,表示购买 s=socket(AF_INET,SOCK_DGRAM) timeout = ip.TIMEOUT s.settimeout(timeout) info={} info["request"]="buygood" info["good_id"]=self.goods_id[self.listWidget.currentRow()] info["good_price"]=self.goods_price[self.listWidget.currentRow()] info["user_id"]=str(self.user_id) info["shop_id"]=str(self.shop_id) info["timestamp"]=ip.get_time_stamp() info = json.dumps(info) res=ip.encrypt(info)#encrypt s.sendto(res,(ip.HOST,ip.PORT)) data,ADDR = s.recvfrom(ip.BUFFERSIZE) data=ip.decrypt(data) data=eval(data) if data["state"]=="succeed": string="Good Name: "+self.goods_name[self.listWidget.currentRow()]+"\n"+"Good ID: "+str(self.goods_id[self.listWidget.currentRow()])+"\n"+"Good Price: "+str(self.goods_price[self.listWidget.currentRow()])+"\n"+"Num Left: "+str(data["num"]) self.listWidget.item(self.listWidget.currentRow()).setText(string) if data["num"]==0: self.listWidget.takeItem(self.listWidget.row(self.listWidget.item(self.listWidget.currentRow()))) self.remain_update.emit() else: self.act_fail.emit() s.close()
def receive_admin_argument(self,dic): #接收管理员信息 self.clear_everything() self.show() self.id=dic["id"] self.name=dic["name"] self.CurrentAdminLine.setText(str("Admin: " + self.name)) s=socket(AF_INET,SOCK_DGRAM) timeout = ip.TIMEOUT s.settimeout(timeout) info={} info["request"]="headimage" info["id"]=self.id info["authority"]="admin" info["timestamp"]=ip.get_time_stamp() info = json.dumps(info) res=ip.encrypt(info)#encrypt s.sendto(res,(ip.HOST,ip.PORT)) data,ADDR = s.recvfrom(ip.BUFFERSIZE) data=ip.decrypt(data) with open('tmp/image.jpg', 'ab') as f: #显示接收的管理员头像 f.write(data) pixmap=QtGui.QPixmap("tmp/image.jpg").scaled(120, 120, transformMode=QtCore.Qt.SmoothTransformation) self.HeadImage.setPixmap(pixmap) os.remove(str("tmp/image.jpg"))#attention s.close()
def callback(frame): ''' The action after receiving datagram from link layer. First unpack datagram Case1: if the outside datagram is received by destination end router, it will first do NAT and update datgram, then push upward Case2; if the internal datagram is received by destination, no need for NAT, directly push upward Case3: if this datagram is received in core routers, find the next forwarding hop ip and convert into mac, then send it by linklayer :param frame: received datagram from linklayer :return: None ''' network, transport, action = unpack(frame) if action == ACTION_PUSH: if network.dst_ip == util.get_local_ipv4_address(): IP.push(frame) elif network.dst_ip in forwarding_table: forwarding_ip = forwarding_table[network.dst_ip] if forwarding_ip != WAN_ip: dst_ip = forwarding_ip else: dst_ip = network.dst_ip if dst_ip != forwarding_ip: print('forwaring to', forwarding_table[network.dst_ip]) dst_mac = util.ip2mac(dst_ip) linklayer.sendto(dst_mac, frame) elif (network.dst_ip, transport.dst_port) in NAT_in : network.dst_ip, transport.dst_port = NAT_in[(network.dst_ip, transport.dst_port)] frame = pack(network, transport) IP.push(frame) else: ICMP.host_unreachable(WAN_ip, network.src_ip)
def cheungssh_login(request): info = {"msgtype": "ERR", "content": "", "auth": "no"} client_ip = request.META['REMOTE_ADDR'] print '登录:', client_ip try: print IP.find(client_ip) except Exception, e: print '不能解析IP'
def cheungssh_login(request): info={"msgtype":"ERR","content":"","auth":"no"} client_ip=request.META['REMOTE_ADDR'] print '登录:',client_ip try: print IP.find(client_ip) except Exception,e: print '不能解析IP'
def sort_proxyip(pool): result = { "all": set(), "china": set(), "foreign": set(), "high_anonymous": set(), "low_anonymous": set(), "non_anonymous": set(), } for ip in pool: # country info = IP.find(ip[0]).strip().replace("\t", "-") ip_ = ip + (info, ) result["all"].add(ip_) if info.startswith("中国"): result["china"].add(ip_) else: result["foreign"].add(ip_) # anonymous if ip[2] == 3: result["high_anonymous"].add(ip_) elif ip[2] == 2: result["low_anonymous"].add(ip_) else: result["non_anonymous"].add(ip_) return result
def login_auth_check(request,*args,**kws): if request.method=='POST': request_content=request.POST else: request_content=request.GET callback=request.GET.get('callback') info={} info['time']=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) info['url']= "%s?%s" %(request.META['PATH_INFO'],request.META['QUERY_STRING']) info['ip']=request.META['REMOTE_ADDR'] info['page']=page info['request_content']=request_content info['ip_locate']=IP.find(info['ip']) isAuth=False if request.user.is_authenticated(): info["username"]=request.user.username isAuth=True if isAuth: if isRecord: _info=json.dumps(info,encoding="utf8",ensure_ascii=False) REDIS.lpush("CHB-R0000000010A-A",_info) return func(request,*args,**kws) else: backinfo={'status':'login'} backinfo=json.dumps(backinfo,encoding="utf8",ensure_ascii=False) if callback: info="%s(%s)" % (callback,backinfo) else: info="%s" % (backinfo) return HttpResponse(info)
def iploc(): # get client real ip ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr) # FIXME: get the client: os type, os version, app version loc = None country = province = city = None is_success = True loc_d = None try: loc = IP.find(ip) if loc: tmp = loc.split() if len(tmp) == 3: (country, province, city) = tmp elif len(tmp) == 2: (country, province) = tmp elif len(tmp) == 1: country = tmp[0] loc_d = {'country': country, 'province': province, 'city': city} except: is_success = False loc_d = None res = json.dumps({"success": is_success, "data": loc_d}) current_app.logger.debug(ip) current_app.logger.debug(res) return res
def cheungssh_login(request): info = {"msgtype": "ERR", "content": "", "auth": "no"} logintime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) client_ip = request.META['REMOTE_ADDR'] limit_ip = 'fail.limit.%s' % (client_ip) ip_threshold_r = cache.get('ip.threshold') ip_threshold = lambda x: x if x is not None else 4 ip_threshold = ip_threshold(ip_threshold_r) if cache.has_key(limit_ip): if cache.get(limit_ip) > ip_threshold: info['content'] = "无效登陆" cache.incr(limit_ip) cache.expire(limit_ip, 8640000) info = json.dumps(info) return HttpResponse(info) if request.method == "POST": username = request.POST.get("username", '非法用户名') password = request.POST.get("password", False) print username, password, request.POST user = authenticate(username=username, password=password) if user is not None: if user.is_active: print "成功登陆" login(request, user) request.session["username"] = username info["msgtype"] = "OK" info['auth'] = "yes" info['content'] = "成功登录" request.session.set_expiry(0) if cache.has_key(limit_ip): cache.delete(limit_ip) print request.COOKIES, request.session.keys( ), request.session['_auth_user_id'] info['sid'] = str(request.session.session_key) else: info["content"] = "用户状态无效" print info["content"] else: if cache.has_key(limit_ip): cache.incr(limit_ip) else: cache.set(limit_ip, 1, 3600) info["content"] = "用户名或密码错误" info["IP"] = client_ip info["IP-Locate"] = IP.find(client_ip) info["username"] = username info["logintime"] = logintime redis_to_redis.set_redis_data( 'sign.record', json.dumps(info, encoding='utf-8', ensure_ascii=False)) else: info["content"] = "No Get" info = json.dumps(info, encoding="utf-8", ensure_ascii=False) response = HttpResponse(info) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST" response["Access-Control-Allow-Credentials"] = "true" return response
def add_black_cmd(request): info={"msgtype":"ERR"} cmd=request.GET.get('cmd') callback=request.GET.get('callback') black_cmd_list=cache.get('black.cmd.list') create_user=request.user.username create_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) client_ip=request.META['REMOTE_ADDR'] IP_locate=IP.find(client_ip) id=str(random.randint(90000000000000000000,99999999999999999999)) CMD={ "id":id, "owner":create_user, "createtime":create_time, "ip":client_ip, "IPlocate":IP_locate, "cmd":cmd } if black_cmd_list is None:black_cmd_list=[] black_cmd_list.insert(0,CMD) cache.set('black.cmd.list',black_cmd_list,8640000000) info["msgtype"]="OK" info["cid"]=id info=json.dumps(info,encoding='utf-8',ensure_ascii=False) if callback is None: info=info else: info="%s(%s)" % (callback,info) response=HttpResponse(info) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST" response["Access-Control-Allow-Credentials"] = "true" return response
def get_title(domain): domain_t = IP._getDomainStr(domain) #print domain_t # 根据传递进来的 domain 获取 首先直接打开网站获取到 title 然后再去修改 header的值 去对比titie # 如果网站本来就打不开呢 打得开 获取 title 打不开直接 输出title try: http_domain = u'http://' + unicode(domain_t[0]) u = u'(' + http_domain + '.*?)"' u2 = u'' + http_domain + u'(.*)' t = u'<title>.*</title>' _re_title = re.compile(t) _re_url = re.compile(u2) abc = 'http://' + domain.strip() r = requests.get(abc, verify=False, allow_redirects=True) url = _re_url.findall(r.url)[0] get1 = _re_url.findall('http://' + domain)[0] if get1 == '': get1 = '/' r1 = get( domain_t[0], 80, __http_header.replace('{host}', domain_t[0]).replace('{url}', get1)) r2, code = x2Unicode(r1) title = _re_title.findall(r2)[0] print 'Get key words:\n"' + title.decode('utf-8') + '"' u_title, code = x2Unicode(title) return url, u_title, domain_t[0] except Exception as a: print a.message #return url,'1',domain_t[0] return 0
def show_ip_limit(request): info={"msgtype":"ERR","content":[]} callback=request.GET.get('callback') R=cache.master_client ip_limit_list=[] for t in R.keys(): if re.search(':1:fail\.limit.*',t): ip=re.sub(':1:fail\.limit\.','',t) ip_time=cache.get('fail.limit.%s' % (ip)) ip_threshold_r=cache.get('ip.threshold') ip_threshold=lambda x:x if x is not None else 4 ip_threshold=ip_threshold(ip_threshold_r) if ip_time> ip_threshold: ip_status="已锁定" else: ip_status="未超过阈值" ip_limit={"ip":ip,"ip-locate":IP.find(ip),"time":ip_time,"status":ip_status} ip_limit_list.append(ip_limit) info["content"]=ip_limit_list info["msgtype"]="OK" info=json.dumps(info,encoding="utf-8",ensure_ascii=False) if callback is None: info=info else: info="%s(%s)" % (callback,info) response=HttpResponse(info) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST" response["Access-Control-Allow-Credentials"] = "true" return response
def login_auth_check(request, *args, **kws): callback = request.GET.get('callback') info = {} info['accesstime'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) info['URL'] = "%s?%s" % (request.META['PATH_INFO'], request.META['QUERY_STRING']) info['IP'] = request.META['REMOTE_ADDR'] info['IPLocat'] = IP.find(info['IP']) isAuth = False #默认为认证不通过,简化下面else的重写 if request.user.is_authenticated(): info["username"] = request.user.username isAuth = True else: info["username"] = "******" #####写入redis ,该值为list,因为username是重复的, 如果用dict,记录会被覆盖 login_record = cache.get('login_record') if login_record: login_record.append(info) else: login_record = [info] if isRecord: cache.set('login_record', login_record, 86400000) #写入redis #####写入redis if isAuth: return func(request, *args, **kws) else: backinfo = {'msgtype': 'login'} #重写信息,该信息是返回给web的,不影响后台的info记录 backinfo = json.dumps(backinfo) if callback: info = "%s(%s)" % (callback, backinfo) else: info = "%s" % (backinfo) return HttpResponse(info)
def testAddLinTermOK(self): testIP = IP.IP_ip() test1 = varFac.fieldVar("x") test2 = varFac.fieldVar("y") ltp = test1 + test2 testIP.addTerm(ltp) self.assertIsNotNone(testIP)
def register_to_persistence(self): s = socket.socket() # Create a socket object #host = '172.17.23.17' # just to show to bibhas sir----- ip_ob = IP.IP() my_ip = ip_ob.get_my_ip() #self.ip = my_ip host = my_ip #--------------------------------- #host = '172.26.35.147' port = 9935 # Reserve a port for your service. s.connect((host, port)) message = " 1:JOIN server" # message format to join #message = raw_input() # get message as input from terminal s.send(message) msg = s.recv(1024) self.nodeid = msg[:msg.rfind(':') - 1] self.A_server = msg[msg.rfind(':') + 1:] print msg s.close() print('connection closed')
def __init__(self, master_port) : self.MASTER_PORT= int(master_port) # this is the port where client(3rd tier) and server(2nd tier) will listen #self.PORT_Mapper = port_mapper.PortMap() self.ip = "" connection_type = 1 print "GOING TO INITIALIZE IP ADDRESS" while True : try : if connection_type == 1 : self.ip = ni.ifaddresses('enp1s0')[2][0]['addr'] else : self.ip = ni.ifaddresses('eth0')[2][0]['addr'] if self.ip == "" : continue except : self.ip = ni.ifaddresses('eth0')[2][0]['addr'] finally : break ip_ob = IP.IP() # Get the ip of the system (machine_ip for master) my_ip = ip_ob.get_my_ip() self.ip = my_ip self.socket_obj = {} self.HOST = self.ip print "Initiating master ",my_ip self.master_node = master_8.Master(self.MASTER_PORT) # creating the master using file master_8.py
def get_customer_in_shop(self): #获取当前店内顾客信息 s=socket(AF_INET,SOCK_DGRAM) timeout = ip.TIMEOUT s.settimeout(timeout) info={} info["request"]="get_customer_in_shop" info["shop_id"]=str(self.shop_id) info["timestamp"]=ip.get_time_stamp() info = json.dumps(info) res=ip.encrypt(info)#encrypt s.sendto(res,(ip.HOST,ip.PORT)) data,ADDR = s.recvfrom(ip.BUFFERSIZE) data=ip.decrypt(data) data=eval(data) self.cus_list.emit(data)
def Pack_tcp_packet(ip_src,port_src,ip_dst,port_dst,mac_src,mac_dst,flags,**kwargs): tcp = TCP.TCP(ip_src,port_src,ip_dst,port_dst,"") if "urg" in flags: tcp.set_urg() if "ack" in flags: tcp.set_ack() if "psh" in flags: tcp.set_psh() if "rst" in flags: tcp.set_rst() if "syn" in flags: tcp.set_syn() if "fin" in flags: tcp.set_fin() if "acknowledgment_number" in kwargs: tcp.acknowledgment_number = kwargs["acknowledgment_number"] if "sequence_number" in kwargs: tcp.sequence_number = kwargs["sequence_number"] if "payload" in kwargs: tcp.payload= kwargs["payload"] tcp_header = tcp.Pack() ip = IP.IP(ip_src,ip_dst,tcp_header) ip_header = ip.Pack() mac_src = Convert_mac_address(mac_src) mac_dst = Convert_mac_address(mac_dst) ethernet = Ethernet.Ethernet(mac_src,mac_dst,0x0800,ip_header) packet = ethernet.Pack() return packet,tcp.sequence_number
def findaddress(t, user_id, ip): '''t=1:注册时查找ip t=2:兑换时查找ip''' import IP ip_address = IP.find(ip) mysql = torndb.Connection(**config['mysql']) if t == 1: mysql.execute( "UPDATE `users` set `ip_address`=%s WHERE `uid`=%s", ip_address, user_id)
def sort_proxyip(pool): result = { "all": set(), "china": set(), "foreign": set(), "high_anonymous": set(), "low_anonymous": set(), "non_anonymous": set(), } for ip in pool: # country info = IP.find(ip[0]).strip().replace("\t", "-") ip_ = ip + (info,) result["all"].add(ip_) if info.startswith("中国"): result["china"].add(ip_) else: result["foreign"].add(ip_) # anonymous if ip[2] == 3: result["high_anonymous"].add(ip_) elif ip[2] == 2: result["low_anonymous"].add(ip_) else: result["non_anonymous"].add(ip_) return result
def isCHINA(self, url): """ # 获取IP 并判断是否为国内网站 返回IP和归属地 :param url: :return: """ ret = [] try: ip = socket.gethostbyname(self.getDomain(url)) ser = IP.find(ip) if not ser: return else: if ser.find('中国') != -1: ret.append(ip) if ser.count("\t") == 2: ret.append(str(re.findall("\t(.*)\t", ser)[0])) else: ret.append(str(re.findall("\t(.*)", ser)[0])) return ret else: return except Exception as e: print(e) return
def login_auth_check(request,*args,**kws): if request.method=='POST': request_content=request.POST else: request_content=request.GET callback=request.GET.get('callback') info={} info['accesstime']=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) info['URL']= "%s?%s" %(request.META['PATH_INFO'],request.META['QUERY_STRING']) info['IP']=request.META['REMOTE_ADDR'] info['page']=page info['request_content']=request_content info['IPLocat']=IP.find(info['IP']) isAuth=False if request.user.is_authenticated(): info["username"]=request.user.username isAuth=True else: info["username"]="******" login_record=cache.get('login_record') if not login_record:login_record=[] login_record.insert(0,info) if isRecord: cache.set('login_record',login_record,8640000000) if isAuth: return func(request,*args,**kws) else: backinfo={'msgtype':'login'} backinfo=json.dumps(backinfo) if callback: info="%s(%s)" % (callback,backinfo) else: info="%s" % (backinfo) return HttpResponse(info)
def get(self): r = self.get_argument('r', '') if not r: self.write('参数错误') return openid = utils.decrypt(r) user_agent = self.request.headers.get('User-Agent', '') platform = utils.get_platform(user_agent) # 判断用户系统是否已知 user_info = users.get_info(openid) if not user_info['platform']: ip = self.request.remote_ip ip_address = IP.find(ip) users.set_ip(openid, ip, ip_address, platform) if user_info['status'] == -2: self.write("非法用户") return if platform == 2: url = urlparse.urljoin(constants.SITE_BASEURL, 'v1/applist/goandroid') self.redirect(url, False, 302) return aes = AESCipher() r = aes.encode(openid) url = 'http://w.ymapp.com/wx/ios/lists.html?r=%s' % r #url = 'http://au.youmi.net/wx/ios/lists.html?r=%s' % r self.redirect(url, False, 302)
def login_auth_check(request,*args,**kws): callback=request.GET.get('callback') info={} info['accesstime']=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) info['URL']= "%s?%s" %(request.META['PATH_INFO'],request.META['QUERY_STRING']) info['IP']=request.META['REMOTE_ADDR'] info['IPLocat']=IP.find(info['IP']) isAuth=False #默认为认证不通过,简化下面else的重写 if request.user.is_authenticated(): info["username"]=request.user.username isAuth=True else: info["username"]="******" #####写入redis ,该值为list,因为username是重复的, 如果用dict,记录会被覆盖 login_record=cache.get('login_record') if login_record: login_record.append(info) else: login_record=[info] if isRecord: cache.set('login_record',login_record,86400000) #写入redis #####写入redis if isAuth: return func(request,*args,**kws) else: backinfo={'msgtype':'login'}#重写信息,该信息是返回给web的,不影响后台的info记录 backinfo=json.dumps(backinfo) if callback: info="%s(%s)" % (callback,backinfo) else: info="%s" % (backinfo) return HttpResponse(info)
def login_auth_check(request, *args, **kws): callback = request.GET.get("callback") info = {} info["accesstime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) info["URL"] = "%s?%s" % (request.META["PATH_INFO"], request.META["QUERY_STRING"]) info["IP"] = request.META["REMOTE_ADDR"] info["IPLocat"] = IP.find(info["IP"]) isAuth = False if request.user.is_authenticated(): info["username"] = request.user.username isAuth = True else: info["username"] = "******" login_record = cache.get("login_record") if login_record: login_record.append(info) else: login_record = [info] if isRecord: cache.set("login_record", login_record, 86400000) if isAuth: return func(request, *args, **kws) else: backinfo = {"msgtype": "login"} backinfo = json.dumps(backinfo) if callback: info = "%s(%s)" % (callback, backinfo) else: info = "%s" % (backinfo) return HttpResponse(info)
def login_auth_check(request, *args, **kws): callback = request.GET.get('callback') info = {} info['accesstime'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) info['URL'] = "%s?%s" % (request.META['PATH_INFO'], request.META['QUERY_STRING']) info['IP'] = request.META['REMOTE_ADDR'] info['IPLocat'] = IP.find(info['IP']) isAuth = False if request.user.is_authenticated(): info["username"] = request.user.username isAuth = True else: info["username"] = "******" login_record = cache.get('login_record') if login_record: login_record.append(info) else: login_record = [info] if isRecord: cache.set('login_record', login_record, 86400000) if isAuth: return func(request, *args, **kws) else: backinfo = {'msgtype': 'login'} backinfo = json.dumps(backinfo) if callback: info = "%s(%s)" % (callback, backinfo) else: info = "%s" % (backinfo) return HttpResponse(info)
def writeFileLine(ip): ports = r_client.sort(address_10(ip)) if ports: port_list = [] port_list.append([x.decode("utf-8") for x in ports]) line = ip + "\t" + "[" + ",".join(port_list[0]) + "]\t" + IP.find(ip) + "\n" ip_data.writelines(line)
def ip2city(ip): try: city = IP.find(str(ip)) if city: city = city.encode('utf-8') else: return None except Exception, e: return None
def IP2city(geo): try: city = IP.find(str(geo)) if city: city = city.encode('utf-8') else: return None except Exception, e: return None
def IP2city(geo): try: city=IP.find(str(geo)) if city: city=city.encode('utf-8') else: return None except Exception,e: return None
def ip2geo(ip): try: city = IP.find(str(ip)) if city: city.encode('utf-8') else: city='' except Exception, e: city = ''
def test_ip(self): poissonForm = PoissonFormulation.PoissonFormulation(2, True) poissonBF = poissonForm.bf() mesh = MeshFactory.MeshFactory_rectilinearMesh(poissonBF, [1.0, 1.0], [2, 3], 4) s = Solution.Solution_solution(mesh) ip = IP.IP_ip() s.setIP(ip) success = s.ip()
def ip2geo(ip): try: city = IP.find(str(ip)) if city: city.encode('utf-8') else: city = '' except Exception, e: city = ''
def cheungssh_login(request): info={"msgtype":"ERR","content":"","auth":"no"} logintime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) client_ip=request.META['REMOTE_ADDR'] limit_ip='fail.limit.%s'%(client_ip) ip_threshold_r=cache.get('ip.threshold') ip_threshold=lambda x:x if x is not None else 4 ip_threshold=ip_threshold(ip_threshold_r) if cache.has_key(limit_ip): if cache.get(limit_ip)>ip_threshold: info['content']="无效登陆" cache.incr(limit_ip) cache.expire(limit_ip,8640000) info=json.dumps(info) return HttpResponse(info) if request.method=="POST": username = request.POST.get("username", '非法用户名') password = request.POST.get("password", False) print username,password,request.POST user=authenticate(username=username,password=password) if user is not None: if user.is_active: print "成功登陆" login(request,user) request.session["username"]=username info["msgtype"]="OK" info['auth']="yes" info['content']="成功登录" request.session.set_expiry(0) if cache.has_key(limit_ip):cache.delete(limit_ip) print request.COOKIES,request.session.keys(),request.session['_auth_user_id'] info['sid']=str(request.session.session_key) else: info["content"]="用户状态无效" print info["content"] else: if cache.has_key(limit_ip): cache.incr(limit_ip) else: cache.set(limit_ip,1,3600) info["content"]="用户名或密码错误" info["IP"]=client_ip info["IP-Locate"]=IP.find(client_ip) info["username"]=username info["logintime"]=logintime redis_to_redis.set_redis_data('sign.record',json.dumps(info,encoding='utf-8',ensure_ascii=False)) else: info["content"]="No Get" info=json.dumps(info,encoding="utf-8",ensure_ascii=False) response=HttpResponse(info) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST" response["Access-Control-Allow-Credentials"] = "true" return response
def testIP(self): poissonForm = PoissonFormulation.PoissonFormulation(2, True) poissonBF = poissonForm.bf() mesh = MeshFactory.MeshFactory_rectilinearMesh(poissonBF, [1.0, 1.0], [2, 3], 4) soln = Solution.Solution_solution(mesh) testIP = IP.IP_ip() soln.setIP(testIP) worked = soln.ip() self.assertIsNotNone(worked)
def resolv_client(request): ip=request.META['REMOTE_ADDR'] username=request.user.username now_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) info={ "ip":ip, "ip_locate":IP.find(ip), "time":now_time, "owner":username, } return info
def receive_info(self,dic): #获取当前顾客信息 self.show() self.shop_id=dic["shop_id"] self.user_id=dic["user_id"] self.UserNameLine.setText("Current User: "******"user_name"]) self.CurrentShopIDLine.setText("Current Shop: "+str(dic["shop_id"])) #user in s=socket(AF_INET,SOCK_DGRAM) timeout = ip.TIMEOUT s.settimeout(timeout) info={} info["request"]="user_in_shop" info["shop_id"]=str(self.shop_id) info["user_id"]=str(self.user_id) info["timestamp"]=ip.get_time_stamp() info = json.dumps(info) res=ip.encrypt(info)#encrypt s.sendto(res,(ip.HOST,ip.PORT)) #change??????? s.close()
def geo2city(geo): # 将geo字段解析为地址 try: city = IP.find(str(geo)) #print city if city: city = city.encode('utf-8') else: return None except Exception,e: print e return None
def find_ip(self,ip): data = IP.find(ip) if data: try: province = data.strip().split('\t') if len(province) == 2: return province[1] else: return province[0] except Exception, e: print data
def ip2city(ip): try: city = IP.find(str(ip)) if city: city = city.encode('utf-8') else: return None city_list = city.split('\t') if len(city_list)==4: city = '\t'.join(city_list[:3]) except Exception,e: return None
def excutecmd(request): info={'msgtype':'ERR','content':[]} if request.method=='POST': callback=request.POST.get('callback') cmd=request.POST.get('cmd') rid=request.POST.get("rid") else: callback=request.GET.get('callback') cmd=request.GET.get('cmd') rid=request.GET.get("rid") ie_key=rid excute_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) client_ip=request.META['REMOTE_ADDR'] client_ip_locat=IP.find(client_ip) username=request.user.username try: server=eval(cmd) cmd=server['cmd'] selectserver=server['selectserver'] if not selectserver:raise IOError("没有选择执行主机") Data=DataConf.DataConf() a=threading.Thread(target=cheungssh_web.main,args=(cmd,ie_key,selectserver,Data)) a.start() allconf=cache.get('allconf') allconf_t=allconf['content'] server_ip_all=[] for sid in selectserver.split(','): server_ip=allconf_t[sid]['ip'] server_ip_all.append(server_ip) cmd_history=cache.get('cmd_history') if cmd_history is None:cmd_history=[] tid=str(random.randint(90000000000000000000,99999999999999999999)) cmd_history_t={ "tid":tid, "excutetime":excute_time, "IP":client_ip, "IPLocat":client_ip_locat, "user":username, "servers":server_ip_all, "cmd":cmd } f**k={} f**k['go']=client_ip_locat cmd_history.insert(0,cmd_history_t) cache.set('cmd_history',cmd_history,8640000000) info['msgtype']="OK" except Exception,e: print "发生错误",e info['msgtype']='ERR' info['content']=str(e)
def validatePacket(packet): if not IP.validateChecksumZero(packet[0:20]): return False, "IP" else: print "IP VALIDATION: SUCCESS" ip_header = IP.unpackHeader(packet[0:20]) #Get Length of IP header ip_ver = ip_header[0] >> 4 ip_header_length = ip_header[0] & 0xF ip_length = ip_header_length * 4 tcp_packet = packet[ip_length:] pseudo = pack('!4s4sBBH', ip_header[8], ip_header[9], 0, socket.IPPROTO_TCP, len(tcp_packet)) if not TCP.validateChecksumZero(pseudo + tcp_packet): return False, "TCP" else: print "TCP VALIDATION: SUCCESS" return True, ""
def ip2city(ip): school = '' try: city = IP.find(str(ip)) if city: city = city.encode('utf-8') else: return None, None city_list = city.split('\t') if len(city_list)==4: city = '\t'.join(city_list[:3]) if 'хнж' in city_list[-1]: school = city_list[-1] except Exception,e: return None, None
def ip2school(ip): school = '' #try: city = IP.find(str(ip)) if city: city = city.encode('utf-8') else: return None city_list = city.split('\t') if len(city_list) == 4 and 'хнж' in city_list[-1]: school = city_list[-1] #except Exception, e: # return None return school
def find_address(ip): country = "unknown" proivnce = "unknown" city = "unknown" address = IP.find(ip) if address: details = address.split("\t") if len(details) > 0: country = details[0] if len(details) > 1: proivnce = details[1] if len(details) > 2: city = details[2] return country,proivnce,city
def ip2geo(ip_list): ip_list = list(ip_list) city_set = set() for ip in ip_list: try: city = IP.find(str(ip)) if city: city.encode('utf-8') else: city = '' except Exception, e: city = '' if city: len_city = len(city.split('\t')) if len_city==4: city = '\t'.join(city.split('\t')[:2]) city_set.add(city)
def post(self): params = {} for key in ['phone', 'smscode', 'password', 'imei', "channel" ,'version_code']: params[key] = self.arguments.get(key, "") if int(params['version_code'])<8: return self.return_error(constants.ERR_IN_VERSION) err = captcha.check_sms(params['phone'], params['smscode']) if err: return self.return_error(err) err = self._check_input(params['phone'], params['imei']) if not err: #pwd = utils.encrypt_pwd(params['password'], None) # print `pwd` + 'en_pwd' ip = self.request.remote_ip ip_address = IP.find(ip) data = channel.get_id(str(params['channel'])) if not data: pkg = 0 else: pkg = int(data['id']) #if params['channel'] == "default": # pkg = 0 #elif params['channel'] == 'YC106': # pkg = 3 #elif params['channel'] == 'YMJFQ': # pkg = 4 user_id = users.new_user(ip, ip_address, params['phone'], params['password'], params['imei'], pkg) wallad_click = wallad_clicks.get_callback_byimei(params['imei']) if wallad_click: callback_url = wallad_click['callback_url'] msg = '' try: msg = str(urllib2.urlopen(callback_url).read()) except urllib2.HTTPError,e: msg = str(e.code) except urllib2.URLError,e: msg = str(e) utils.loggers.use('device', self.config['log']['adyoumi']).info('[youmi_callback]:'+msg) self.db.execute( "UPDATE `wallad_clicks` set `status`=1,`uid`=%s, `msg`=%s \ WHERE `id`=%s", user_id, msg, wallad_click['id']) wallad_clicks.set_user_pkg(user_id, 2)
def post(self): openid = self.get_argument('openid', '') if not openid: self.return_result(constants.ERR_INVALID_PARAMS) return price = self.get_argument('price', 0) if price.isdigit() and int(price) <= 0: self.return_result(constants.ERR_PRICE_NULL) return user_info = users.get_info(arg['openid']) points = int(price) * 1000 if user_info['points'] < points: self.return_result(constants.ERR_NOT_POINTS) return oid = orders.new_global_order(user_info['uid'], -points, user_info['points'], orders.ORDER_TYP_EXCHANGE, u'云南地震捐款 %s 元' % price) ip = self.requests.remote_ip ip_address = IP.find(ip) p = { 'uid': user_info['uid'], 'oid': oid, 'ip': ip, 'ip_address': ip_address, 'points': points, 'total_points': points, 'price': price, 'total_price': price, 'goods_id': 1, 'goods_title': u"捐款 %s 元" % price, 'count': 1, 'status': 13, 'address_type': 0, 'address': user_info['name'], 'notes': u"%s 捐款 %s 元" % (user_info['name'], price), 'orderNum': None, 'type': None, } orders.new_exchange_order(p) users.sub_exchange_points(user_info, points) self.return_result((0, '捐款成功!'))
def ip2geo(ip_dict): city_set = set() geo_dict = dict() for ip in ip_dict: try: city = IP.find(str(ip)) if city: city.encode("utf-8") else: city = "" except Exception, e: city = "" if city: len_city = len(city.split("\t")) if len_city == 4: city = "\t".join(city.split("\t")[0:3]) try: geo_city[city] += ip_dict[ip] except: geo_dict[city] = ip_dict[ip]
def ip2geo(ip_dict): city_set = set() geo_dict = dict() for ip in ip_dict: try: city = IP.find(str(ip)) if city: city.encode('utf-8') else: city = '' except Exception, e: city = '' if city: len_city = len(city.split('\t')) if len_city==4: city = '\t'.join(city.split('\t')[:2]) try: geo_dict[city] += ip_dict[ip] except: geo_dict[city] = ip_dict[ip]
def excutecmd(request): info={'msgtype':'ERR','content':[]} callback=request.GET.get('callback') cmd=request.GET.get('cmd') rid=request.GET.get("rid") ie_key=rid excute_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) client_ip=request.META['REMOTE_ADDR'] client_ip_locat=IP.find(client_ip) username=request.user.username try: server=eval(cmd) cmd=server['cmd'] selectserver=server['selectserver'] Data=DataConf.DataConf() a=threading.Thread(target=cheungssh_web.main,args=(cmd,ie_key,selectserver,Data)) a.start() info['msgtype']="OK" except Exception,e: info['content']=str(e)
def _new_user(self): # ip = str(self.request.headers.get('X-Real-Ip', '')).split(',')[0] scode = self._user_params.pop('scode' ,'') cne = self._user_params.pop('cne') pkg = cne if scode == 'qianlu_pkg1': pkg = 1 if pkg == '': pkg = 0 user_params = { "ip": self.request.remote_ip, "ip_address": IP.find(self.request.remote_ip), "pkg": pkg, } # 渠道点击统计,先写入redis,再通过脚本将redis中的数据同步到数据库,每小时执行一次 value = self.redis.get("qianka:channel_click:"+cne) if not value: value = 0 self.redis.set("qianka:channel_click:"+cne,1) else: value = int(value)+1 self.redis.set("qianka:channel_click:"+cne,value) utils.loggers.use('channel_click', self.config['log']['channel_click']).info("channel:"+`cne`+" "+`value`) uid = users.new_user(**user_params) if int(pkg) == 5: users.flow_user(uid, 1) self._user_params['uid'] = uid users.new_device(**self._user_params) # 是否邀请,考虑使用队列来减少接口处理时间 FIXME if scode and (scode!='qianlu_pkg1'): self._set_invite(uid, scode) key_name = "qianka:scode:%s" % uid self.redis.setex(key_name, scode, 600) return uid