您的位置:首页技术文章
文章详情页

Python sql注入 过滤字符串的非法字符实例

浏览:20日期:2022-07-31 10:05:14

我就废话不多说了,还是直接看代码吧!

#coding:utf8#在开发过程中,要对前端传过来的数据进行验证,防止sql注入攻击,其中的一个方案就是过滤用户传过来的非法的字符def sql_filter(sql, max_length=20): dirty_stuff = [''', '', '/', '*', '’', '=', '-', '#', ';', '<', '>', '+', '%', '$', '(', ')', '%', '@','!'] for stuff in dirty_stuff: sql = sql.replace(stuff, '') return sql[:max_length]username = '1234567890!@#!@#!@#$%======$%'username = sql_filter(username) # SQL注入print username# 输出结果是:1234567890

补充知识:python解决sql注入以及特殊字符

python往数据库插入数据,

基础做法是:

cur=db.cursor()sql = 'INSERT INTO test2(cid, author, content) VALUES (1, ’1’, ’aa’)'cur.execute(sql,())

也可以这样:

cur=db.cursor()sql = 'INSERT INTO test2(cid, author, content) VALUES (%s, ’%s’, ’%s’)'sql=sql%(’2’,’2’,’bb’)cur.execute(sql,())

但是当含有特殊一点的字符时就有问题了,比如单引号,%等,甚至会被sql注入。

和其他语言一样,python也他的方法来解决sql注入。

cur=db.cursor()sql = 'INSERT INTO test2(cid, author, content) VALUES (%s, %s, %s)'cur.execute(sql,(’3’,’3’,’c%c’))

注意,后面2个%s的前后单引号去掉了。

结果如下:

Python sql注入 过滤字符串的非法字符实例

以上这篇Python sql注入 过滤字符串的非法字符实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Python 编程
相关文章: