In: Computer Science
Make sure you name files with test_yourname in question 1, 4, and 5
Q1: Add a user named as test_yourname in linux terminal. Take a screenshot if it has been added to the system file /etc/passwd
Q2: What is grep? And why is it used for? (2 lines only)
Q3: Use grep over a file of your choice, take a screenshot and explain the results.
Q4: Can you store the output of top command in a file named as: test_yourname.txt in such a way that the file is appended and not rewritten? Take a screen shot.
Q5: Set password length policy for test_yourname user, with minimum length of password to be 10 character long.
1. Added logic to take username and password from user
Instead of taking from user, we can statically define the same variables in program and use them directly.
cat output of /etc/passwd file
To directly add logged in user, you can use username="${whoami}", to direclt add the logged in username.
2. grep is a command line utility for searching any txt files/ string for a matching 'regex'
Ex: In the above screenshot, I have serached for 'gowthami' in password file, if there exists any line containing 'gowthami' it will output the line, otherwise the output will be empty.
3. The above screenshot matches the case of using grep over passwd file.
4. The code do a redirect of top to file, giving ctrl+c breaks the copy operation, and every time we run the script this appends to existig file
#!/bin/bash
while true; do
echo "$(top -b -n 1)" | tee -a top-output.log #This redirects output of top to top-output.log file
sleep 1
done
5. Case where password doesn't meet the requirements (>=10 lower case charecters )
Case meething the requirements
Code to validate the password
#!/bin/bash
if [[ $# -ne 2 ]]; then
echo "Script requires 2 arguments"
exit
fi
username=$1
password=$2
echo $password | grep -q -E "[a-z]{10}" #Verifying password meets requirements of length is 10 or more charecters
if [[ $? -eq 0 ]]; then #if, yes
useradd -m -p $password $username
else
echo "Password length doesn't match the requirements"
fi
For your reference, to validate password of length 10 or more characters with at least 1 lower, 1 upper case, 1 digit and 1 special character
echo $password | grep -q -E "[A-Za-z0-9@#$%^&*]{10}" #Verifying password meets requirements of at least 1 Upper, 1 lower, 1 digit, 1 special character and length is 14 or more characters