How can I pass commands to SSH when using expect while it doesn't support using double quotes?

53 Views Asked by At

I'm automating my login process to my servers using an inline bash script, I'm using expect to automate this, but upon logging into server I also want to print a message, I didn't had any luck with echo because I read in a stackoverflow post that it's not reliable cause I want to use color coding, now I'm using printf to do this, printf works in the server perfectl but when passing it in this little script of mine I'm getting an error, I suspect that there is something wrong with the way I'm using curly braces instead of double quotes, I will be glad if someone can point out what is wrong with the way I'm putting the printf command in curly braces.

expect -c 'spawn ssh -t MYHOST@MYSERVER {printf [\33[01;32m A MESSAGE TO BE SHOWN \33[01;37m]\n; bash}; expect "Password:"; send "MY PASSWORD"; interact'

I'm getting these errors, there is absolutely something wrong with the I'm putting printf command inside curly braces:

bash: {printf: command not found bash: 32m: command not found bash: 37m]n}}: command not found

I tried using double quotes and many ways of using curly braces but didn't have any luck.

Thank you everyone.

2

There are 2 best solutions below

2
Philippe On BEST ANSWER

You need to put quotes around printf :

expect -c 'spawn ssh -t  MYHOST@MYSERVER "printf '"'"'\[\\33\[01\;32m\ \ A\ MESSAGE\ TO\ BE\ SHOWN\ \ \\33\[01\;37m\]\\n'"'"'; bash"; expect "Password:"; send "secret\r"; interact'

The command to run on the server is printf '...', as expect -c used the single quote, we need '"'"'.

If you think alternating quotes are confusing, you can use '\''

0
glenn jackman On

An alternative to Philippe's answer: leave the braces but just put single quotes around the printf argument

expect -c '
  spawn ssh -t user@host {printf '\''[\33[01;32m  A MESSAGE TO BE SHOWN  \33[01;37m]\n'\''; bash}
  expect "Password:"
  send "MY PASSWORD"
  interact
'

Or, even cleaner, use a quoted heredoc and you don't need to anything special with the single quotes.

expect << 'END_EXPECT'
  spawn ssh -t user@host {printf '[\33[01;32m  A MESSAGE TO BE SHOWN  \33[01;37m]\n'; bash}
  expect "Password:"
  send "MY PASSWORD"
  interact
END_EXPECT