TransWikia.com

how to send special characters in expect script?

Unix & Linux Asked by user2925298 on November 26, 2021

I’m trying to send special characters (password) which contains #?!k;|C .
The password is dynamic and cannot be hardcoded in the script, so I’m passing it as variable as shown below

$ expect ./passwordlessSSH.exp $hostname "$password"

the code of this script is as below

#!/usr/bin/expect -f
 set host [lindex $argv 0]
set pass [lindex $argv 1]

spawn ssh-copy-id -i /home/hdpsvcs/.ssh/id_rsa.pub hdpsvcs@$host
expect {
  "yes" {
    send "yesr"
  }
    "assword" {
    send "$pass r"
}
exit 0

But still it is not running the script properly. I don’t see any error but the variable is not passed correctly. The output is as shown below:

$ expect ./passwordlessSSH.exp $hostname "$password"

 spawn ssh-copy-id -i /home/hdpsvcs/.ssh/id_rsa.pub test@otesthost
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed:
"/home/test/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are     prompted now it is to install the new keys
S
Kernel r on an m
test@test's password: 
$

One Answer

After plenty of searching, I realized I couldn't use expect with special character unless i escaped. Convert password with special characters for use with expect script gives a short perl script that allowed me to handle special characters programatically in dynamic passwords.

#/bin/sh
pstr='$x%y!zpass' # plain, un-escaped string
estr=$(perl -e 'print quotemeta shift(@ARGV)' "${pstr}")
echo ${estr}      # show escaped string

produces:

$x%y!zpass

Edit: I was unable to send it to an expect script from the command line, so feel free not to accept this as the answer, but using the above did work for me by sending arguments to a bash script, that in turn invokes the expect script. Here's how I'd apply it to the OP's code.

Bash script: passwordlessSSH.sh

#/bin/sh
hostname=$1
pstr=$2 # plain, un-escaped string
estr=$(perl -e 'print quotemeta shift(@ARGV)' "${pstr}")
echo ${estr}      # show escaped string
/your/script/location/passwordlessSSH.exp $hostname ${estr}

Expect Script: passwordlessSSH.exp

#!/usr/bin/expect -f
set host [lindex $argv 0]
set pass [lindex $argv 1]

spawn ssh-copy-id -i /home/hdpsvcs/.ssh/id_rsa.pub hdpsvcs@$host
expect {
  "yes" {
    send "yesr"
   }
    "assword" {
    send "$pass r"
}
exit 0

To execute: Just execute the bash script

./passwordlessSSH.sh $hostname "$password"

Answered by Byte on November 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP