It appears that nobody else has addressed the obvious concern here. Putting sudo
within your script that you then distribute promotes bad user habits. (I'm assuming you're distributing it because you mention "from a user point of view.")
The truth is that there is a guideline in using applications and scripts which is similar to the security principle in banking of: Never give out your personal information to someone who calls you and says they're calling "from your bank", and which exists for similar reasons.
The rule for applications is:
Never type in your password when prompted unless you are certain what is being done with it. This applies triply to anyone with sudo
access.
If you're typing your password in because you ran sudo
on the command line, great. If you're typing it in because you ran an SSH command, fine. If you're typing it in when you log in to your computer, great, of course.
If you just run a foreign script or executable and tamely enter your password when prompted for it, you have no idea what the script is doing with it. It could be storing it in a temp file in plaintext, for all you know, and might even fail to clean up after itself.
Obviously there are separate and additional concerns about running an unknown set of commands as root
, but what I'm talking about here is maintaining security on the password itself. Even assuming the application/script is not malicious, you still want your password to be handled securely to prevent other applications from getting hold of it and using it maliciously.
So, my own personal response to this is, the best thing to put in your script if it needs root privileges, is:
#!/bin/bash
[ "$UID" -eq 0 ] || { echo "This script must be run as root."; exit 1;}
# do privileged stuff, etc.