Home Database Mysql Tutorial Python操作MySQL时防止SQL注入

Python操作MySQL时防止SQL注入

Jun 07, 2016 pm 05:05 PM
mysql python

下面是网上搜到的一篇关于SQL注入的文章。最近在项目中涉及到防止SQL注入的部分,但是由于使用的是PYTHON和MYSQL,使用不了JAVA代

下面是网上搜到的一篇关于SQL注入的文章。最近在项目中涉及到防止SQL注入的部分,但是由于使用的是PYTHON和MYSQL,使用不了JAVA代码中提供的一些现成的方法,而且MYSQLDB模块中的EXECUTE方法不支持表名使用占位符。

execute(self,query, args=None)

Execute a query.

query -- string, query to execute on serverargs -- optional sequence or mapping, parameters to use with query.

Note: If args is a sequence, then %s must be used as theparameter placeholder in the query. If a mapping is used,%(key)s must be used as the placeholder.

Returns long integer rows affected, if any

Placeholders are supposed to be used for *values*, not other parts of the SQL statement. To insert table names, column names and stuff like that, use Python-level formatting.

cur.execute("select * from %s where name=%s",('t1','xx'))   --python-level formatting,执行失败

cur.execute("select * from %s where name=%s"%('t1','xx'))  --execute()-level formatting,执行成功,但是并没有达到防止SQL注入的效果

下面是文档上的一个例子

To perform a query, you first need a cursor, and then you can executequeries on it:

In this example, max_price=5 Why, then, use%s in thestring? Because MySQLdb will convert it to a SQL literal value, whichis the string '5'. When it's finished, the query will actually say,"...WHERE price

无奈之下手工实现,,需要两步:

1、把变量值中的单引号逃逸掉

2、给变量值两端加上单引号

#######################
应该说,您即使没有处理 HTML 或 JavaScript 的特殊字符,也不会带来灾难性的后果,但是如果不在动态构造 SQL 语句时对变量中特殊字符进行处理,将可能导致程序漏洞、数据盗取、数据破坏等严重的安全问题。网络中有大量讲解 SQL 注入的文章,感兴趣的读者可以搜索相关的资料深入研究。

虽然 SQL 注入的后果很严重,但是只要对动态构造的 SQL 语句的变量进行特殊字符转义处理,就可以避免这一问题的发生了。来看一个存在安全漏洞的经典例子:

以上 SQL 语句根据返回的结果数判断用户提供的登录信息是否正确,如果 userName 变量不经过特殊字符转义处理就直接合并到 SQL 语句中,黑客就可以通过将 userName 设置为 “1' or '1'='1”绕过用户名/密码的检查直接进入系统了。

所 以除非必要,一般建议通过 PreparedStatement 参数绑定的方式构造动态 SQL 语句,因为这种方式可以避免 SQL 注入的潜在安全问题。但是往往很难在应用中完全避免通过拼接字符串构造动态 SQL 语句的方式。为了防止他人使用特殊 SQL 字符破坏 SQL 的语句结构或植入恶意操作,必须在变量拼接到 SQL 语句之前对其中的特殊字符进行转义处理。Spring 并没有提供相应的工具类,您可以通过 jakarta commons lang 通用类包中(spring/lib/jakarta-commons/commons-lang.jar)的 StringEscapeUtils 完成这一工作:

清单 4. SqlEscapeExample

 

事实上, StringEscapeUtils 不但提供了 SQL 特殊字符转义处理的功能,还提供了 HTML、XML、JavaScript、Java 特殊字符的转义和还原的方法。如果您不介意引入 jakarta commons lang 类包,我们更推荐您使用 StringEscapeUtils 工具类完成特殊字符转义处理的工作。

linux

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

How to call docker lnmp How to call docker lnmp Apr 15, 2025 am 11:15 AM

Docker LNMP container call steps: Run the container: docker run -d --name lnmp-container -p 80:80 -p 443:443 lnmp-stack to get the container IP: docker inspect lnmp-container | grep IPAddress access website: http://<Container IP>/index.phpSSH access: docker exec -it lnmp-container bash access MySQL: mysql -u roo

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

What's going on with vscode not running python What's going on with vscode not running python Apr 15, 2025 pm 06:00 PM

The most common "cannot run Python" problem stems from the misconfiguration of the Python interpreter path. Solutions include: confirming Python installation, configuring VS Code, and using a virtual environment. In addition, there are efficient debugging techniques and best practices such as breakpoint debugging, variable monitoring, log output, and code formatting, such as isolating dependencies using virtual environments, tracking code execution using breakpoints, and tracking variable changes in real time using monitoring expressions, etc., which can greatly improve development efficiency.

See all articles