Problem statement
I want to access a server without asking me the password (will be mentioned in the script) and run a command on that server.
My Code
#!/usr/bin/expect
spawn sudo su - <server_name>
expect "[sudo] password for chronicles:"
set Password "xxxxxxx"
send "$Password\r"
#set timeout 300
send "whoami\r"
send "ls -ltr\r"
expect eof
Output
invalid command name "sudo"
while executing
Restrictions
- I dont have access rights to change env variables or modify
.bash_profile / .bashrc. - su server_name command not allowed
David is right that generally this is a bad idea. There are occasionally good reasons for doing it, or doing something similar (e.g. automatically logging into serial consoles for lights-out management), but you haven’t provided any indication as to why it makes sense for you to do it this way.
Caveats aside, the
invalid command nameis not coming from thespawnline but from the[sudo]in theexpectline. Expect is based ontcl, which treats[]square parentheses as special characters indicating command substitution. Additionally, the value passed toexpectis a glob pattern not a fixed string, and[]square parentheses are also special characters in globs. So the answer you are looking for is to quote those characters twice:Also note that after sending the password you should probably include another
expectline to wait for the root shell prompt.