在终端(ubuntu)中发出请求/命令并将答案保存在 mysql 中

在终端(ubuntu)中发出请求/命令并将答案保存在 mysql 中

我正在寻找一个批处理程序,以便在终端(对于 ubuntu)中执行小命令,并在同一台计算机的 mysql 数据库中保存答案。

例如,我想每小时询问一次计算机的温度,并将答案保存在已创建的数据库中。我不知道是否应该使用 php 或批处理来连接到数据库并保存信息,但我不知道如何实现这两种可能性。

请帮助。

再见。

答案1

这在 Python 中很容易实现。首先,学习如何获取 CPU 的温度这里。使用命令sensors或将cat /sys/class/thermal/thermal_zone0/temp当前温度写入临时文件curr.temperature。您可以在 bash 脚本或 Python 程序本身中单独执行此操作,使用:

from subprocess import call
call (["/path/to/script/get_temperature"], shell=False)

然后 Python 代码只需要读取文件curr.temperature并将值存储在 MySQL 表中。我没有测试过这段代码,但它应该是这样的:

#!/usr/bin/python
import MySQLdb.cursors
with open('curr.temperature', 'r') as f:
    read_data = f.read() 
db = MySQLdb.connect(db='databasename', host='localhost',
                     port=3306, user='MySQL-username', passwd='password',
                     cursorclass=MySQLdb.cursors.DictCursor)
cur = db.cursor()
cur.execute("INSERT INTO temperatures VALUES (now," + read_data + ")" )

相关内容