I'm trying to write a bash script which, among several other things, will "log in" as a user (preferably with su if possible) without needing to interact with the password prompt, i.e., will automatically input the password. I only need it to perform one command and then the session can end.

This is for an "automatic checker" for an introductory Linux class I'm teaching. The students have an exercise where they create usernames with specific passwords on their Raspberry Pis (running Raspbian), and I want this script to automatically verify the passwords are correct. The students run the "automatic checker" on their Pis and I verify the output, so they have a chance to fix any errors before turning in. Since this is for a classroom exercise with dummy passwords, the security of these passwords is completely irrelevant.

I know there are already a few questions about automatic logins, but none of them work for me. The closest I've come to a solution is getting the su command to say a terminal is required. Using "expect" will not work because it will require installing packages on the students' Pis.

If there are other ways to verify the passwords are correct then I'm open to those. I don't think I can do a hashed password comparison due to the salt.

  • I've agreed to the suggested duplicate since I am confident I could've pieced something together based on the accepted answer (even though it apparently incorrectly says it can't be done in pure shell tools) and this answer had I found that question during my search, but for the record I believe the answer here is much better. – tilper Nov 18 at 13:54

if you have root :

salt=$(awk -F\$ '$1 ~ /student:/ { print $3 }' /etc/shadow)
hashedpasswd=$(awk -F: '$1 == "student" { print $2} ' /etc/shadow)
expected=$(mkpasswd -m sha-512 given-passwd $salt)
if [ "$hashedpasswd" = "expected" ]
   echo good
   echo bad
  • replace student by revellant string of course.
  • replace given-passwd as well.

see my question for more details : /etc/shadow : how to generate $6$ 's encrypted password?

  • 1
    I got something working based on this. For some reason I couldn't use that salt=$(...) line inside the script even though it worked from the command line. It seemingly didn't like the variable I was using inside the loop for some reason. But I replaced it with $(grep "$name:" /etc/shadow | awk -F "$" '{print $3}') and this works perfectly. Thanks a lot! – tilper Nov 17 at 17:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.