【问题标题】:User input with $$ messes up Variable [duplicate]使用 $$ 的用户输入搞砸了变量 [重复]
【发布时间】:2021-10-30 02:15:54
【问题描述】:

我正在尝试通过命令行参数从用户那里获取用户名和密码。

我的问题是,如果我使用像 Test$$123 这样的密码,它会看到 $$ 广告 PID 并弄乱用户密码。现在是Test4365123$1$2 等也是如此。

有什么办法可以摆脱这种“解释”而获得“真正的”价值?

注意:问题发生在pass=$2,所以我不能转义任何字符。 (我尝试过的):)

这是我的代码:


# Input
TEMP=`getopt -o ap: --long admin:,pass: -n 'add-vhost' -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
eval set -- "$TEMP"
while true; do
  case "$1" in
    -a | --admin ) admin="$2"; shift 2 ;;
    -p | --pass ) pass="$2"; shift 2 ;;
    -- ) shift; break ;;
    * ) exit; break ;;
  esac
done

echo $admin
echo $pass

【问题讨论】:

  • 请尝试将` `更改为TEMP=$(...)?你的getopt --version 输出是什么?
  • @KamilCuk verion: 2.33.1 和变化它仍然是一样的
  • 您为什么使用eval 而不仅仅是seteval 肯定会插入字符串。
  • 你在做类似./script --pass "Test$$123"的事情吗?您的脚本永远不会看到 $$;在script 甚至运行之前,它已被shell 扩展为当前进程ID。
  • @KamilCuk bash ./test.bash --admin user --pass Test$$123 是命令行。我说密码之类的,因为用户密码可能会更改,并且密码中可能是 $1。

标签: bash variables


【解决方案1】:

bash ./test.bash --admin user --pass Test$$123 是命令行。

$$ 被扩展之前你的脚本甚至运行。您必须引用或转义特殊字符,例如 $,以防止它们被扩展。

bash ./test.bash --admin user --pass 'Test$$123'
# or
bash ./test.bash --admin user --pass Test\$\$123

【讨论】:

  • 是的,我试过了,一切都很好,但我不能问用户所以寻找任何 $ 符号并转义它们:(所以它必须由脚本处理
  • 脚本无法处理。脚本永远不会看到它。如果用户不知道如何使用 shell,则不应允许他们运行您的脚本。
  • but I cant ask the user 从你的脚本来看,用户输入了Test4365123。如果用户不希望$$ 被扩展,用户可以不使用shell。用户正在运行以输入行的 shell 正在扩展 $$
  • 从另一个角度来看,密码不应作为命令行参数传递,因为机器上的任何人都可以看到这些参数。该脚本可能会提示输入可以从终端读取的密码(not 标准输入),或者更好的是,让实际需要密码的程序执行提示。
【解决方案2】:

如果用户无法正确使用 shell,您可以更改 --pass 以简单地提示用户输入他们的密码。从标准输入读取,字符串不会被shell扩展。

# Changes: -p and --pass do not take arguments; they are
# just used to change the value of get_pass from 0 to 1.
TEMP=`getopt -o ap: --long admin:,pass -n 'add-vhost' -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
eval set -- "$TEMP"
get_pass=0
while true; do
  case "$1" in
    -a | --admin ) admin="$2"; shift 2 ;;
    -p | --pass ) get_pass=1 ;;
    -- ) shift; break ;;
    * ) exit; break ;;
  esac
done

# Read the password directly from the terminal (not standard
# input). If you do want to allow reading from standard input,
# remove the input redirection.
#
# Remove -s if you want the user to be able to see the password
# as they type.
if [[ "$get_pass" = 1 ]]; then
    read -ps 'Password: ' pass < /dev/tty
fi

echo $admin
echo $pass

【讨论】:

  • getopt: unrecognized option '--admin' Try 'getopt --help' for more information. Terminating... 这个输出
  • (@o'gamingSCV 请注意,如果您想删除您的评论,我已经彻底修改了这个答案。)
猜你喜欢
  • 2016-02-11
  • 2017-06-15
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
相关资源
最近更新 更多