SQL注入

什么是 SQL 注入?
- 利用 SQL 中的一些特殊语法,绕过了 SQL 语句

import pymysql

conn = pymysql.connect(
  host='127.0.0.1',
  port=3306,
  user='root',
  password='xxxxx',
  database='练习题',
  charset='utf8',
  autocommit=True,
)

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

userid = input('请输入用户名>>>: ').strip()
userpwd = input('请输入密码>>>: ').strip()

sql = "select * from t1 where name='%s' and pwd='%s'" % (userid, userpwd)

cursor.execute(sql)

res = cursor.fetchone()
if res:
  print('登录成功')
else:
  print('登录失败')

下图是表 t1 中的内容
在这里插入图片描述

示例一、
请输入用户名>>>: ly' -- xxxxxx
请输入密码>>>: 333
  
'在密码错误的情况下仍可成功登录'
将 sql 打印可知
select * from t1 where name='ly' -- xxxxxx' and pwd='333''-- 'SQL语句中表示注释的意思,因此之后的代码并不执行,直接跳过,因此输入密码已失去意义

如下图
在这里插入图片描述

示例二、
请输入用户名>>>: egon ' or 1=1 -- xxxx
请输入密码>>>: 

将 sql 打印可知
select * from t1 where name='egon ' or 1=1 -- xxxx' and pwd=''
在账户名输入错误的情况下,使用 or 跳过错错误选项,引用一个恒成立的结果,并跳过密码同样可以达到登录账户的目的

如下图
在这里插入图片描述

解决 SQL 注入问题

import pymysql

conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    password='xxxxx',
    database='练习题',
    charset='utf8',
    autocommit=True,
)

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

userid = input('请输入用户名>>>: ').strip()
userpwd = input('请输入密码>>>: ').strip()

sql = "select * from t1 where name='%s' and pwd='%s'"

cursor.execute(sql, (userid, userpwd))  # 使用 pymsql 模块的 excute 语句,并遵循其语法即可过滤特殊符号,解决 SQL 注入问题

res = cursor.fetchone()
if res:
    print('登录成功')
else:
    print('登录失败')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值