6、sql注入

sql注入:指通过把sql命令插入到web表单提交或输入域名或页面请求的查询字符串中,最终达到欺骗服务器并且执行恶意sql指令的目的。

防止:

  1. 对用户的输入进行校验,通过正则表达式或限制长度,对单引号和--进行转换
  2. 不要使用动态拼装sql
  3. 不要使用管理员权限的数据库连接,为每个应用使用单独的权限有限的数据库连接
  4. 将机密信息加密如hash
  5. 使用自定义的错误信息代替应用的原始的错误信息
  6. sql注入检测可通过辅助软件(jsky:Web漏洞扫描软件,是一款针对与网站漏洞扫描的安全软件)或网站平台(亿思:免费Web漏洞扫描平台)

如下:mysql中username为qwe,password为123

import pymysql

user = input('username:')
pwd = input('password:')

con = pymysql.connect(host='127.0.0.1', user='root', password='win',database='lx')
cur = con.cursor()
sql = "select * from userinfo WHERE username='%s' and password='%s'"%(user,pwd)
cur.execute(sql)
result = cur.fetchone()

cur.close()
con.close()
if result:
    print('welcome')

注入:

username:' or 1=1 -- ''    #注入
password:
select * from userinfo WHERE username='' or 1=1 -- ''' and password=''
welcome

防止:

import pymysql

user = input('username:')
pwd = input('password:')

con = pymysql.connect(host='127.0.0.1', user='root', password='win',database='lx',charset='utf8')
cur = con.cursor()
sql = "select * from userinfo WHERE username=%s and password=%s"  #不在这里拼接
cur.execute(sql,[user,pwd])    #写入execute中
result = cur.fetchone()

cur.close()
con.close()
if result:
    print('welcome')

sql及execute中写法:

1、列表

sql = "select * from userinfo WHERE username=%s and password=%s"
cur.execute(sql,[user,pwd])

2、元组

sql = "select * from userinfo WHERE username=%s and password=%s"
cur.execute(sql,(user,pwd))

3、字典

sql = "select * from userinfo WHERE username=%(u)s and password=%(p)s"
cur.execute(sql,{'u':user,'p':pwd})
渐变 --> 突变
原文地址:https://www.cnblogs.com/lybpy/p/8244354.html