2

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
Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
Dev
  • 21
  • 2
  • would you please read this answer https://unix.stackexchange.com/questions/187339/spawn-command-not-found –  Oct 13 '18 at 14:37
  • 1
    @Goro, thanks alot. Given link is very helpful. My Problem solved. Thanks aton – Dev Oct 13 '18 at 14:53
  • take a look at [*sexpect*](https://github.com/clarkwang/sexpect) with which you can write *Expect* scripts with shell code only. – UNIX.root Oct 15 '18 at 03:14

1 Answers1

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/

glenn jackman
  • 84,176
  • 15
  • 116
  • 168