Shell scripting is a powerful way to automate things. However, writing a shell script to automate interactive shell commands can be tricky. For instance, I weekly download log files from the server to my local machine. For this, I use scp command. While I had written shell script to automate this process, it wasn’t really an automation. The scp command requires password, which I cannot pass as a parameter but has to be entered interactively. Thus, my script wasn’t really an automation. To overcome this specific issue (entering password for using scp command), you can use RSA key as suggested here. However, this would only solve the password problem. Also for a newbie like me who is entered the Mac world recently, this seemed to be much more involving. I was looking for an approach that was much more generic, simple and less geeky.
Luckily, today I came across another solution that satisfy all of my above constraints. However, the simplicity of this second approach approach comes with the price of being less secure. As explained here, the second solution is to use the “expect” command. For instance below a sample code that shows how to use expect command to write an interactive shell script.
In order to get the above code, however, make sure you have following things correctly done:
- Make sure the first line is correct: The first line should be address leading to the location where the compiler/interpreter (not sure) can find expect command. Usually it is at /usr/bin/. If you not sure, open a terminal and type “which expect”. This will tell the location where the compiler can find the expect command. Also include trailing -f
- Spawn: Include “spawn” before all your commands
- exp_continue: Also include exp_continue after sending the password
- Running the file using ./: Normally we run a shell script using the “/bin/sh file_to_execute.sh”. If you try running the code using this method, it will generate errors. Make sure you run the code using “./file_to_execute.sh“
Expect command, as used above, is not limited to sending password but can be used to send any other parameter. See the original post for an example.This make expect command much more generic than using RSA key. However, as you might have notice that you have explicitly type the password in the file. Anyone with system administrator privileges can easily open you shell script and look at the password. Hence, as I said before, the simplicity of the “expect” command tradeoffs security. Nevertheless, I am quite thrilled to find this and having fun with my new or real automation script.