sql注入攻击

# ###sql 注入攻击
# 创建一张表

create table usr_pwd(
id int unsigned primary key auto_increment,
username varchar(255) not null,
password varchar(255) not null
)

# (1)sql注入问题

import pymysql
user=input("user:>>>").strip()
pwd=input("pwd:>>>").strip()
conn=pymysql.connect(host="localhost",user="root",password="123456",database="testdb1")
cursor=conn.cursor()
sql="select * from usr_pwd where username='%s' and password='%s'"%(user,pwd)
"""注意,username='%s'和password='%s'要加引号,因为数据库中username和password都是字符串型"""
""" 注入攻击(1): r734d' or 2=2 -- dfe23 实际执行的sql语句: select * from usr_pwd where username='r734d' or 2=2 -- dfe23' and password=''
# 这里
-- 后面的语句表示注释
注入攻击(2)(更简单): 
' or 1 #
实际执行的sql语句: select * from usr_pwd where username='' or 1 #' and password=''
"""
print(sql)
res
=cursor.execute(sql)
print(res) #返回查询到的条数
if res:
  print("登录成功")
else:
  print("登录失败")
cursor.close()
conn.close()

# (2) 解决办法

使用预处理机制,可以避免绝大多数的sql注入问题;
execute 默认参数是一个sql语句 ,如果把sql语句和参数值分开执行,就开启预处理
execute(sql,(参数1,参数2,参数3 ..... ) )

import pymysql
user=input("user>>>").strip()
pwd=input("pwd>>>").strip()
conn=pymysql.connect(host="127.0.0.1",user="root",password="123456",database="testdb1")
cursor=conn.cursor()
sql="select * from usr_pwd where username=%s and password=%s"
res=cursor.execute(sql,(user,pwd))

if res:
    print("登录成功")
else:
    print("登录失败")
cursor.close()
conn.close()
原文地址:https://www.cnblogs.com/banbosuiyue/p/11967729.html