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
What it is and how it works. Passwordless authentication is a means to verify a user's identity, without using a password. Instead, passwordless uses more secure alternatives like possession factors (one-time passwords [OTP], registered smartphones), or biometrics (fingerprint, retina scans).
Done right, implementing passwordless authentication is not disruptive, it is not traumatic to users and it will significantly improve your overall security posture by eliminating the attack vectors associated with shared secrets.
Passwordless SSO allows multi-factor authentication (MFA) to be leveraged to its full potential. By improvising on traditional MFA authentication procedures with advanced cryptographic protocols, passwordless SSO places another layer of protection around enterprise applications.
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 name
is not coming from the spawn
line but from the [sudo]
in the expect
line. Expect is based on tcl
, which treats []
square parentheses as special characters indicating command substitution. Additionally, the value passed to expect
is 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:
expect "\\\[sudo\\\] password for chronicles:"
Also note that after sending the password you should probably include another expect
line to wait for the root shell prompt.
The secure way to access a server without prompting for a password is through keyed logins over SSH. Don't ever give your password in plain text.
If you simply Google, you will find many articles explaining how to do this. SSH login without password is a perfectly fine explanation.
[]
is interpreted as "command quotes" ("command" as in "Tool Command Language", which is what Tcl
is short for) in Tcl
.
{}
is the strongest quote in Tcl
, you can use it to prevent any interpretation:
expect {[sudo] password for chronicles:}
of course you could also just omit [sudo]
:
expect "password for chronicles:"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With