Python和pymysql-无法通过MySQL执行系统命令

时间:2018-12-06 11:19:17

标签: python mysql linux ubuntu

我在Python中有以下代码,该代码使用pymysql库连接到MySQL的本地根数据库:

#!/usr/bin/python3
import pymysql

db = pymysql.connect("localhost", "root", "redacted", "redacted")

cursor = db.cursor()
query = "INSERT INTO TestTable (text) VALUES ('test');"
cursor.execute(query)
db.commit()

上面的代码工作正常,但是如果我需要执行系统命令(根据MySQL CLI语法),例如:

query = "system ls -lah;" 
query = "INSERT INTO TestTable (text) VALUES ('test'); system ls -lah;" 
query = "\! ls -lah" 

我收到以下令人困惑的错误:

Traceback (most recent call last):
  File "./app.py", line 9, in <module>
    cursor.execute(query)
  File "/usr/local/lib/python3.6/dist-packages/pymysql/cursors.py", line 170, in execute                                                       
    result = self._query(query)
  File "/usr/local/lib/python3.6/dist-packages/pymysql/cursors.py", line 328, in _query                                                        
    conn.query(q)
  File "/usr/local/lib/python3.6/dist-packages/pymysql/connections.py", line 516, in query                                                     
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)                                                                       
  File "/usr/local/lib/python3.6/dist-packages/pymysql/connections.py", line 727, in _read_query_result                                        
    result.read()
  File "/usr/local/lib/python3.6/dist-packages/pymysql/connections.py", line 1066, in read                                                     
    first_packet = self.connection._read_packet()
  File "/usr/local/lib/python3.6/dist-packages/pymysql/connections.py", line 683, in _read_packet                                              
    packet.check_error()
  File "/usr/local/lib/python3.6/dist-packages/pymysql/protocol.py", line 220, in check_error                                                  
    err.raise_mysql_exception(self._data)
  File "/usr/local/lib/python3.6/dist-packages/pymysql/err.py", line 109, in raise_mysql_exception                                             
    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'system ls -lah' at line 1")

这可能是MySQL服务中实现的一个安全问题(因为我在python中使用其他数据库库时遇到了相同的错误),但是如果是这样,我如何调低此设置?

我正在使用最新版本的Ubuntu Server(18.10)和MySQL(对于Linux(x86_64)为Ver 14.14 Distrib 5.7.24)。

编辑:为了澄清一点,我非常了解Python的ossubprocess,但是我想通过MySQL查询尝试上述技术。我还尝试了不同的驱动程序,例如MySQLdbmysql.connector,但所有驱动程序都具有相同的结果。

1 个答案:

答案 0 :(得分:0)

MySQL CLI上的system命令是一项便利功能,可让您发布命令以在默认命令解释器上执行。它不需要或不使用数据库连接。它仅在UNIX系统上可用。
CLI是供管理员或用户使用数据库的工具。它包含一个数据库驱动程序,但也包含一个系统外壳转义符;它试图涵盖管理数据库所需的所有功能。

pymysql(或任何其他符合DB API 2.0的驱动程序包)的构建目的是创建与数据库的连接,从这些连接中获取游标,并在这些游标上执行SQL语句。它不关心系统外壳。
数据库驱动程序是允许开发人员在程序中实现SQL查询功能的软件包。它不需要做更多的事情,因为如果开发人员需要上述程序中的其他功能,他们将使用适当的程序包来实现它。

如果要通过Python脚本发布系统命令,可以将subprocess视为该命令的标准软件包。