As msv pointed out in the comments, the whole premiss sounds like an instance of the of the XY problem and very much a nightmare security wise, but I'll try to address the question of gaining root privileges without a password.
echo "password" | su won't work because
su does not read the password from
stdin, but opens
/dev/tty directly for reading. While there are tools (such as expect) which can be used to automate interactive programs, the approach of automatically gaining a root shell in order to invoke a specific command as root is a bad from a security perspective as it violates the principle of least privilege.
That said, authentication with
su could be automated with
expect using something like the following:
If the goal is to allow the invocation of a specific command as root, without requiring the root credentials, the right tool for the job is
sudo. For instance, if it desired to allow users in the
wheel group to a run
useradd without entering a password, it can be achieved by adding the following stanza to
/etc/sudoers with the
%wheel ALL = NOPASSWD: /usr/sbin/useradd
When setting up such privileges, it is prudent to atleast make sure that the capability is restricted to a particular user or an exclusive group.
As for using this method for adding users via a CGI-script or similar, typically it would not be desirable to grant such privileges directly to web-facing software, but to add a level of privilege separation in between. The actual privileges could be granted to a separate software component, such as a daemon, which the web-application would ask (via IPC) to perform the privileged operation on its behalf. This way input validation could be done both by the privileged process and the web-application, to minimize the risks of exploitable flaws in the web-application allowing the invocation of the privileged operation (
useradd in this case) with arbitrary parameters, or worse, such as the execution of arbitrary code with elevated privileges.