通过bash脚本编程逃避MySQL命令行 [英] Escaping MYSQL command lines via Bash Scripting

查看:109
本文介绍了通过bash脚本编程逃避MySQL命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP有 mysql_real_escape_string()来逃避正确可能导致问题的任何字符。什么是模仿此功能为BASH的最佳方式?

PHP has mysql_real_escape_string() to correctly escape any characters that might cause problems. What is the best way to mimic this functionality for BASH?

反正是有使用bash做prepared MySQL的声明?这似乎是最好的方法。

Is there anyway to do prepared mysql statements using bash? This seems to be the best way.

我的大多数变量不会(也不应该)有特殊字符,但是我给他们的密码,用户完全的自由。它可能包括像人物和

Most of my variables won't (shouldn't) have special characters, however I give the user complete freedom for their password. It may include characters like ' and ".

我可能会做多个SQL语句,所以我会想打一个脚本,在需要的参数,然后运行该语句。这是我到目前为止有:

I may be doing multiple SQL statements so I'll want to make a script that takes in parameters and then runs the statement. This is what I have so far:

doSQL.sh:

#!/bin/sh

SQLUSER="root"
SQLPASS="passwor339c"
SQLHOST="localhost"

SQL="$1"
SQLDB="$2"


if [ -z "$SQL" ]; then echo "ERROR: SQL not defined"; exit 1; fi
if [ -z "$SQLDB" ]; then SQLDB="records"; fi

echo "$SQL" | mysql -u$SQLUSER -p$SQLPASS -h$SQLHOST $SQLDB

和一个例子使用上述命令:

and an example using said command:

example.sh:

example.sh:

PASSWORD=$1
doSQL "INSERT INTO active_records (password) VALUES ('$PASSWORD')"

显然,如果密码密码它包含了一个单引号,这将失败。

Obviously this would fail if the password password contained a single quote in it.

推荐答案

在bash中,的printf 可以做转义为您提供:

In Bash, printf can do the escaping for you:

$ a=''\''"\;:#[]{}()|&^$@!?, .<>abc123'
$ printf -v var "%q" "$a"
$ echo "$var"
\'\"\\\;:#\[\]\{\}\(\)\|\&\^\$@\!\?\,\ .\<\>abc123

我将让你来决定,如果这是侵略性不够。

I'll leave it to you to decide if that's aggressive enough.

这篇关于通过bash脚本编程逃避MySQL命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆