I need help in writing shell script. I am running one command which will ask for Username:, Email address:, Password:, Password (again):.
I need to write script which wait for prompt and feed the input to command. I tried with expect & send but seems not working.
[root@ip-1xx-xx-x-xx hue]$ sudo build/env/bin/hue createsuperuser
Username: xyz
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.`
==============
Tried with below script:
#!/usr/bin/expect -f
cd /usr/lib/hue/
set timeout -1
sudo build/env/bin/hue createsuperuser
expect "Username: "
send -- "admin"
expect "Email address: "
send -- "[email protected]"
expect "Password: "
send -- "Password@123"
expect "Password (again): "
send -- "Password@123"
expect eof
The above script stuck at username
[root@ip-1xx-xx-x-xx ~]$ sh -x hueuser.sh
cd /usr/lib/hue/
set timeout -1
sudo build/env/bin/hue createsuperuser
Username:
CodePudding user response:
I believe the createsuperuser command asks for Username (leave blank to use ‘root’)
, not Username
Try using:
#!/usr/bin/expect -f
cd /usr/lib/hue/
set timeout -1
sudo build/env/bin/hue createsuperuser
expect "Username (leave blank to use ‘root’)"
send -- "admin"
expect "Email address:"
send -- "[email protected]"
expect "Password:"
send -- "Password@123"
expect "Password (again):"
send -- "Password@123"
expect eof
CodePudding user response:
Your expect
script has a few problems still (even after you edited to remove the \r
s in the expect
strings which were also wrong).
First, you will need to spawn
the command you are trying to run. If sudo
works at all here, it will create a subprocess which runs outside of the control of expect
.
Second, you need to send exactly the string you want to send, including the final newline. This is where \r
is useful and necessary.
#!/usr/bin/expect -f
cd /usr/lib/hue/
set timeout -1
spawn sudo build/env/bin/hue createsuperuser
expect "Username: "
send -- "admin\r"
expect "Email address: "
send -- "[email protected]\r"
expect "Password: "
send -- "Password@123\r"
expect "Password (again): "
send -- "Password@213\r"
expect eof
A much better fix if you have control over the createsuperuser
script is to change it so it doesn't require interactive I/O. See for example how the adduser
command on Debian-based platforms wraps the lower-level useradd
to allow it to be called from scripts with all the necessary arguments as command-line arguments. Also, man newusers
for inspiration.