run a sudo command, specifying the password on the same line

sudo does not have an option to specify the password, but you can still do the authentication on the command line, like this:

echo password | sudo -u root --stdin

or just

echo password | sudo -S

referring to the sudo manual page:

-S, --stdin
Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. The password must be followed by a newline character.

and

-u user, --user= user
Run the command as a user other than the default target user (usually root). The user may be either a user name or a numeric user ID (UID) prefixed with the ‘#’ character (e.g. #0 for UID 0). When running commands as a UID, many shells require that the ‘#’ be escaped with a backslash (‘\’). Some security policies may restrict UIDs to those listed in the password database. The sudoers policy allows UIDs that are not in the password database as long as the targetpw option is not set. Other security policies may not support this.

But sudo has been under development a long time. Check the version:

-V, --version
Print the sudo version string as well as the version string of the security policy plugin and any I/O plugins. If the invoking user is already root the -V option will display the arguments passed to configure when sudo was built and plugins may display more verbose information such as default options.

The support for long options was added in 2013.

Besides authenticating, you need something for sudo to do, e.g., a command. I often check that it is working by doing just

sudo id

which should show the root user, e.g.,

uid=0(root) gid=0(root) groups=0(root)

While OP might have a good reason for wanting to do exactly this, it usually is a bad idea (password can be read by ps, and so on) and I wanted to provide a more secure alternative.

A better solution if you want to run something with sudo without putting in your password is to allow your user to do exactly that one command without password.

Open sudoers file with sudo visudo and add the following line (obviously replace the username at the beginning and the command at the end):

alice ALL = NOPASSWD: /full/path/to/command

This is explained more here: https://askubuntu.com/a/39294

Tags:

Sudo