mysql 注入问题

1、实质

MySql语句是用户自行拼接的字符串

2、例子

import pymysql
# 获取用户输入信息
username = input("请输入用户名:")
pwd = input("请输入密码:")
# 连接数据库
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='@WSX3edc',
    database='userinfo',
    charset='utf8'
)
# 获取光标
cursor = conn.cursor()
sql = "select * from info where name='%s' and password='%s';" % (username, pwd)
# 执行MySql语句
print(sql)
ret = cursor.execute(sql)
if ret:
    print("登录成功!")
else:
    print("登录失败!")
# 关闭光标
cursor.close()
# 关闭连接
conn.close()

注入语句

输入语句
losser' or 1=1 #
输出sql语句
select * from info where name='losser' or 1=1 #' and password='';
注意:我这里用pycharm连接MySql,在pycharm中sql语句的注释是:#
如果不通过pycharm连接数据库,而是直接通过pymysql连接 注释应该是: --
select * from info where name='losser' or 1=1 
1=1为永真语句
#' and password='';

3、解决注入问题->通过pymysql模块进行字符拼接

import pymysql
# 获取用户输入信息
username = input("请输入用户名:")
password = input("请输入密码:")
# 连接数据库
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='@WSX3edc',
    database='userinfo',
    charset='utf8'
)
# 获取光标
cursor = conn.cursor()
# sql语句
sql = 'select * from info where name=%s and password=%s;'
# 执行sql语句,通过pymysql进行sql语句拼接
ret = cursor.execute(sql, [username, password])
if ret:
    print("登录成功!")
else:
    print("登录失败!")
# 关闭光标
cursor.close()
# 关闭连接
conn.close()

猜你喜欢

转载自www.cnblogs.com/wt7018/p/11210514.html