Provide Password Using Shell Script

How to provide password to a command that prompts for one in bash?

Take a look at autoexpect (decent tutorial HERE). It's about as quick-and-dirty as you can get without resorting to trickery.

How to give password in shell script?

If you can't use ssh trust and must enter the password later on in your script, use read -s -p "Password:" USER_PASSWORD to silently read in the password. You can then export USER_PASSWORD to an expect script, avoiding it being displayed in ps:

    #!/usr/bin/expect -f
spawn scp some.file USER@otherhost:~
expect "assword:"
send -- "$env(USER_PASSWORD)\r"
expect eof

SHELL SCRIPT LINUX set password using user input

$username:$password should be the input to the chpasswd command. You're piping the output of chpasswd to a command formed from that. Since the username:password isn't the name of a command, you get an error.

What you want is:

chpasswd <<< "$username:$password"

Using the passwd command from within a shell script

from "man 1 passwd":

   --stdin
This option is used to indicate that passwd should read the new
password from standard input, which can be a pipe.

So in your case

adduser "$1"
echo "$2" | passwd "$1" --stdin

[Update] a few issues were brought up in the comments:

Your passwd command may not have a --stdin option: use the chpasswd
utility instead, as suggested by ashawley.

If you use a shell other than bash, "echo" might not be a builtin command,
and the shell will call /bin/echo. This is insecure because the password
will show up in the process table and can be seen with tools like ps.

In this case, you should use another scripting language. Here is an example in Perl:

#!/usr/bin/perl -w
open my $pipe, '|chpasswd' or die "can't open pipe: $!";
print {$pipe} "$username:$password";
close $pipe

Use Expect in a Bash script to provide a password to an SSH command

Mixing Bash and Expect is not a good way to achieve the desired effect. I'd try to use only Expect:

#!/usr/bin/expect
eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com

# Use the correct prompt
set prompt ":|#|\\\$"
interact -o -nobuffer -re $prompt return
send "my_password\r"
interact -o -nobuffer -re $prompt return
send "my_command1\r"
interact -o -nobuffer -re $prompt return
send "my_command2\r"
interact

Sample solution for bash could be:

#!/bin/bash
/usr/bin/expect -c 'expect "\n" { eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com; interact }'

This will wait for Enter and then return to (for a moment) the interactive session.

How to automatically add user account AND password with a Bash script?

You can run the passwd command and send it piped input. So, do something like:

echo thePassword | passwd theUsername --stdin


Related Topics



Leave a reply



Submit