How do you write a bash script for example, a user logins to the server’s shell, then I want a bash script that will prompt him a password to verify he is a legit user not an intruder. The answer of the password will be located in a file (for example: /etc/verify). If the user not able to type the correct password 3 times the server will kill that connection and bans his IP address from the server.
First off, I have to say that while I am a big fan of shell scripts as the universal solution to almost any problem, I am a bit leery about using it as a security screen rather than coding something in C or similar.
But what you ask about can certainly be done. The key is to know that you can turn off input echo with the stty command, leading to a simple script snippet to prompt for a password:
echo -n "Password: "
echo "" # force a carriage return to be output
echo You entered $password
I’ve left blank lines so you can see the three line sequence that lets the password not be shown as the user types it in.
With this script in your toolkit, you then need to grab the correct password from the /etc/verify file:
and then compare the two:
if [ $password = $correct ] ; then ...
If it fails, increment a counter:
failed=$(( $failed + 1 ))
Put those pieces together and you’ll have everything except the action that should happen when they fail three times in a row. To log someone out, you can simply kill their login shell, which can be quickly identified by finding the parent process ID of the script itself, which is typically the third field in a ps -l output.
To block their IP, I assume you’d need to automatically append the IP address to some sort of firewall, but since there are a number of different firewalls, you’re on your own with that last one.
Hope that’s helpful. I’ll leave putting all these building blocks together as an “exercise for the reader”. 🙂