Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I've been curious ever since I've started bash scripting in Ubuntu, and I have been wondering if there was a way to log in as root or run a sudo command without physically typing the password manually when it prompts you in the terminal.

Is it possible to hard-code the password into a line, such as "echo mypassword" and have sudo read through the echo command instead of typing for myself?

I've looked around that you could, if you had set the root to have no password, which is something I do not want.

I've just been playing around with bash and seeing if I could login as root and run a command in root through the bash script only:

#!/bin/bash

echo mypassword | sudo apt-get install frozen-bubble

This is just out of my pure curiosity, and was just wondering how to implement it if it was possible. Thanks.

IF this is relevant, I'm using Ubuntu 9.04.

share|improve this question

4 Answers 4

You should not hardcode your password. If you want use sudo without password, you must edit sudoers file. To edit sudoers, type command

$ sudo visudo

Visudo uses vi as editor. If you are not familiar in vi, you could set environment variable VISUAL or EDITOR to you favourite editor, eg.VISUAL=nano. The following environment variables are used only if visudo was configured with the --with-env-editor

In sudoers file, you should place line

your_username ALL=(ALL) NOPASSWD: ALL

or

%some_groupname ALL=(ALL) NOPASSWD: ALL

or (be careful, this enable sudo without password for all users)

ALL ALL=(ALL) NOPASSWD: ALL

For more information use man sudoers

share|improve this answer
    
+1 sudo is the secure way forward –  Coops Oct 28 '09 at 17:14

You can't and shouldn't hardcode the password in the script. The right way to do this is to make sure that the user running the script is in the sudoers file, and then use sudo in the script.

share|improve this answer

Hardcoding passwords is bad. Use sudo with no password.

share|improve this answer

One other interesting thought here.....use ssh with generated public/private keys. The key can be configured to allow only certain commands to be execute with it.

If you use sudo with no password required, I'd probably make sure that the command set is limited and not ALL.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.