Python后台进程不写入MySQL数据库

标签 python mysql linux

如果之前有人问过这个问题,我深表歉意,但我无法找到此问题的任何记录。全面披露:我只使用 Python 几个月,使用 MySQL 大约 1 个月。

我在 Raspberry Pi(运行 Raspbian Wheezy)上编写了一个简短的 Python 脚本,用于嗅探 wifi 数据包并将信号强度信息写入 MySQL 数据库。我还创建了一个小的 PHP 文件,它从数据库中获取信息并将其呈现在表格中(非常基本)。然而,这个小系统的所有组件都完全按照计划工作......

当我在后台运行 Python 脚本 (sudo python my_script.py &) 时,它似乎没有使用新读数更新 MySQL 数据库。但它也不会抛出任何错误并毫无问题地输出到控制台(每次拦截 wifi 数据包并将其 RSSI 添加到数据库时,我都会打印一行)。使用/etc/rc.local 文件在启动时启动脚本时遇到了同样的问题。没有错误,但数据库中也没有更新。

问题出在Python方面吗?我需要更改 MySQL 设置吗?还有什么我完全想念的吗?

编辑添加代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
import sys
from scapy.all import *

# Create connection to MySQL database called 'DATABASE' at localhost with username 'USERNAME' and password 'PASSWORD'
HOST = "localhost"
USER = "USERNAME"
PW = "PASSWORD"
DB = "DATABASE"

con = mdb.connect(HOST, USER, PW, DB)

# set interface that will be used to monitor wifi
interface = "mon0"

with con:

        cur = con.cursor()

        # This function will be called every time a packet is intercepted. Packet is passed to function as 'p'
        def sniffmgmt(p):

                # These are the 3 types of management frames that are sent exclusively by clients (allows us to weed out packets sent by APs)
                stamgmtstypes = (0, 2, 4)

                if p.haslayer(Dot11):

                        # Make sure packet is a client-only type
                        if p.subtype in stamgmtstypes:

                                # Calculate RSSI
                                sig_str = -(256-(ord(p.notdecoded[-4:-3])))

                                # Update database with most recent detection
                                cur.execute("REPLACE INTO attendance(mac_address, rssi, timestamp) VALUES('%s', %d, NOW())" % (p.addr2, sig_str))

                                # Print MAC address that was detected (debugging only)
                                print "MAC Address (%s) has been logged" % (p.addr2)

        # Tell scapy what interface to use (see above) and which function to call when a packet is intercepted. lfilter limits packets to management frames.
        sniff(iface=interface, prn=sniffmgmt, store=0, lfilter=lambda x:x.type==0)

谢谢! 凯尔

附注对于那些想知道的人:这并不是为了恶意使用,而是用于调查我们仓库的产品跟踪技术。

最佳答案

我希望您不会在数据库事务上调用commit

关于Python后台进程不写入MySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16239590/

相关文章:

python - 透明像素在 PIL 中作为黑色传递

mysql - 执行 'SELECT INTO OUTFILE' 时错误访问被拒绝的 mysqldump 的正确权限是什么?

c - 是否可以使用 C 更改 Linux 终端文本和背景颜色?

c++ - 在 .c 文件中使用 Linux 中的 msgget 创建消息队列接收函数未实现错误

linux - 没有误报风险的高可用性计算 : How to deal with a non-returning system call,?

python - 有没有办法打印 Light GBM 分类器模型最重要特征的列表?

python - 线性 X 对数刻度

Python optparse 回调为函数提供参数

php - MySQL 和 php 中的唯一文本字段

mysql - MySQL中INT和UUID的区别