4

This question already has an answer here:

I want to pass server name which is listed in a file (servers_list) as variable to spawn command which is in another script (user_create_script). Purpose of this script is to create user(david) in multiple servers.

#cat servers_list
server1
server2
server3


#cat user_create_script
    spawn ssh -t user@$i sudo /usr/sbin/useradd david
    expect "password:"
    send "pass123\r"
    interact

marked as duplicate by user88036, Jeff Schaller, G-Man, Romeo Ninov, GAD3R Oct 14 '18 at 11:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

You'd have user_create_script like this

#!/usr/bin/expect -f
set fh [open servers_list r]
while {[gets $fh server_name] != -1} {
    spawn ssh -t user@$server_name sudo /usr/sbin/useradd david
    expect "password:"
    send "pass123\r"
    expect eof
}
close $fh

I assume your remote user does not require a password for sudo.

More documentation about Tcl (upon which expect is built), including tutorials, is here: https://tcl.tk/doc/

Not the answer you're looking for? Browse other questions tagged or ask your own question.