Elixir或Erlang密码提示,带隐藏输入

kkih6yb8  于 2022-12-08  发布在  Erlang
关注(0)|答案(3)|浏览(155)

我正在用elixir编写CLI,如何提示用户输入密码,而不在终端中显示输入内容?

zdwk9cvp

zdwk9cvp1#

You can accomplish this using the Erlang :io.get_password() function, e.g.

IO.write("What is your password?")

password = :io.get_password()
           |> List.to_string()

Note that IO.write/1 is preferable to using Mix.shell().info() for the prompt because the info function will add a newline, which is usually not what you want in a prompt.
Also be advised that :io.get_password() returns input as a charlist, so you will probably want to convert it to a binary as demonstrated above.
I wrote a package that utilizes the above technique: https://hex.pm/packages/cowrie

iq0todco

iq0todco2#

显然这有一些问题。目前最好的解决方案似乎是重复清除循环中的输入,正如在Hex包管理器中实现的那样:
https://github.com/hexpm/hex/blob/1523f44e8966d77a2c71738629912ad59627b870/lib/mix/hex/utils.ex#L32-L58

smdncfj3

smdncfj33#

只需编写如下代码,直接从Mix.Tasks.Hex借用该功能,

some_pass = 
  Mix.Tasks.Hex.password_get("Password: ") 
  |> String.replace_trailing("\n","")

如果您在任务中请求密码,并且不想一遍又一遍地请求密码,则可以将其保存在如下所示的环境变量中:

:os.putenv(String.to_charlist("SECRET_PASSWORD"), String.to_charlist(some_pass))

当然,还可以使用以下方法检索:

System.get_env("SECRET_PASSWORD")

相关问题