0

I would like to mimic the default way of hiding a password on Ubuntu (for example, when using a sudo command), preferably in Lua 5.1.

2 Answers 2

1

I don't know the Ubuntu way, but try this:

io.write("password: ")
io.flush()
os.execute("stty -echo")
password=io.read()
os.execute("stty echo")
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I guess this a way to do it.
Only thing worth knowing here is that should this get interrupted between the two calls to stty the terminal will stay in -echo mode (which might confuse someone).
0
#!/usr/bin/env lua

query = "Enter password: "
valid_chars="[%d%w%p]"
io.write(query)
pwd = ''
length = 0
invalid = {}
os.execute("stty -icanon -echo")
while true do
    local char = io.read(1)
    if char == '\n' or string.byte(char) == 27 then --esc
        break
    elseif char == '\b' or string.byte(char) == 127 then
        if length > 0 then
            io.write('\r' .. string.rep(' ', (string.len(query) + length))) -- clear whole line
            length = length - 1
            pwd = string.sub(pwd, 1, length)
            io.write('\r' .. query .. string.rep('*', length))
        end
    elseif string.match(char, valid_chars) then
        pwd = pwd .. char
        length = length + 1
        io.write('\r' .. query .. string.rep('*', length))
    else
        table.insert(invalid, char)
    end
end
os.execute("stty icanon echo")
if #invalid > 0 then
    print("\nThe following characters are not allowed: '" .. table.concat(invalid, "', '") .. "'")
    print("The password is invalid!")
else
    print("\nPassword is: " .. pwd)
end

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.