在pymysql中防止SQL注入

荒凉一梦 提交于 2019-12-17 06:07:50

sql注入就是在python程序中 改变原有的sql语句的含义 使数据库中的数据全部显示或者部分显示

能注入的原理 提前把SQL语句中的未知项 直接 拼接在SQL语句上

sql = ‘select * from user where uname="%s" and upsw="%s"’ % (name, psw)
如果你输入的那么为"哈哈" or 1 = 1 # \
再去执行这条SQL语句 – 漏洞就出现了 会查询全部数据

具体实现注入代码如下

import pymysql

name = input("请输入用户名: ")
psw = input("请输入密码: ")


con = None
cur = None
try:
    con = pymysql.connect(host="localhost",port=3306,user="root",passwd="123456",database="py1910",charset="utf8")
    if con:
        print("链接成功")
        #获取操作数据库的游标
        cur = con.cursor()

        sql = 'select * from user where uname="%s" and upsw="%s"' % (name, psw)
        print(sql)
        #select * from user where uname = "哈哈" or 1 = 1  # \" and upsw="123"
        #在Python中 #表示的是注释  后面的内容忽略
        # where 后面的条件 一直为 true  那么也就代表着这个where是没有意义的
        # 就等价与 select * from user
        #执行查询语句 查看满足要求的数据的条数
        rows = cur.execute(sql)
        print(rows)

        if rows == 0:
            print("用户名或者密码错误")
        else:
            print("登录成功")

except Exception as e:
    print("异常:",e)
finally:
    if con:
        if cur:
            cur.close()
        con.close()
        

防止过程代码如下

import pymysql

name = input("请输入用户名: ")
psw = input("请输入密码: ")


con = None
cur = None
try:
    con = pymysql.connect(host="localhost",port=3306,user="root",passwd="123456",database="py1910",charset="utf8")
    if con:
        print("链接成功")
        #获取操作数据库的游标
        cur = con.cursor()

        sql = 'select * from user where uname=%s and upsw=%s'
        print(sql)
        #具有验证判断的这种存在未知项的  使用 在execute中进行传值
        rows = cur.execute(sql,[name, psw])  #name = '哈哈" or 1=1 #\'  psw="123"

        print(rows)

        if rows == 0:
            print("用户名或者密码错误")
        else:
            print("登录成功")

except Exception as e:
    print("异常:",e)
finally:
    if con:
        if cur:
            cur.close()
        con.close()


'''

原理:
SQL语句中存在未知项
先去执行SQL语句 — 由于SQL语句不完整
解释器将 SQL当做了函数 未知项是形参
当再给未知项传值时 传入的数据是什么 未知项接触的内容就是什么

现在类似与填空
 题目的主干已经设置好了
 提的准确定就根据填入的内容直接判断  不会被python的解释器干扰
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!