简体   繁体   English

python udp服务器解析并将接收到的数据发送到MySQL

[英]python udp server parse and send received data to MySQL

i am working on some proof of concept study research project and have python udp socket server that listen received data. 我正在研究一些概念验证研究项目,并且有python udp套接字服务器来监听接收到的数据。 Client send data NAME and FAMILY NAME on UDP to server. 客户端通过UDP将数据“ NAME”和“ FAMILY NAME”发送到服务器。 I would like to receive that data on UDP socket server side and on receive send this data to mysql database with two fields f_name and l_name. 我想在UDP套接字服务器端接收该数据,并在接收时将该数据发送到具有两个字段f_name和l_name的mysql数据库。

import socket

UDP_IP = "192.168.1.10"
UDP_PORT = 9000

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
print "UDP SERVER STARTED!"

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print "MSG Received:", data

this example is taken from web and with this server i get data on console. 这个例子取自网络,使用此服务器,我可以在控制台上获取数据。 I would like to have it like below and of course code/concept can be changed. 我想像下面这样,当然可以更改代码/概念。 This might be solved with scapy sniffer but that would be dirty. 这可以用scapy嗅探器解决,但这很脏。 Conceptually i would like to have ti something like: 1. socekt server received data 2. parse data received and send this data to mysql 从概念上讲,我希望拥有以下内容:1. socekt服务器接收到数据2.解析接收到的数据并将此数据发送到mysql

I started with this in mind but doesnt work 我从这个想法开始,但没有用

import socket
import MySQLdb

UDP_IP = "192.168.1.10"
UDP_PORT = 9000

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
print "UDP SERVER STARTED!"

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print "received message:", data

def parse(data):
    db = MySQLdb.connect("localhost","db_user","db_pass","directory_db")
    cursor = db.cursor()
    # Params to insert into DB
    f_nameObj = re.search(r'NAME: (.*?) .*', data, re.M|re.I)
    if f_name:
        f_name = f_nameObj.group(1)

    l_nameObj = re.search(r'SURNAME: (.*?) .*', data, re.M|re.I)
    if l_name:
        l_name = l_nameObj.group(1)

    # MySQL EXECUTION
    cursor.execute("""
    INSERT INTO dictionary (f_name, l_name) VALUES (%s, %s)""",(f_name,l_name))
    #
    db.commit()

With this kind of udp server i see no messages so seems function that parse data is not working with server. 使用这种udp服务器,我看不到任何消息,因此似乎无法解析服务器数据。 Any help or guidance would be appreciated 任何帮助或指导将不胜感激

In your server when you receive data you don't call parse function.You just print the content of data . 在服务器中,当您接收到data您不会调用parse函数。您只需打印data内容即可。 Add the line with the comment and see the result. 添加带有注释的行并查看结果。

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print "received message:", data
    parse(data) # Call the Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM