Except script fails to check file exists or not in remote node

Dear members, The following expect script connects to remote node and check for the file "authorized_keys" in directory /root/.ssh in remote node. However the result is always found even if the file exist or doesn't exist.

expect {
"$fname" {
send_user "found\n"
}

Any idea what is causing this issue and how to fix it please ?

Thanks.

spawn ssh -q -o GlobalKnownHostsFile=/dev/null -o  \
UserKnownHostsFile=/dev/null -o CheckHostIP=no -o StrictHostKeyChecking=no $USER@$SYSTEM
expect "password:"
send "$PASSWORD\n"
expect "$ "
send "mkdir -p .ssh\r"
expect "$ "
set fname /root/.ssh/authorized_keys
set timeout 2
expect {
"$fname" {
send_user "found\n"
}
timeout {
send_user "not found\n"
}
}

You cannot just do expect "$fname" to test the existence of remote files. Try:

expect "$ "
set fname /root/.ssh/authorized_keys
set timeout 2
send "[ -f $fname ] && echo YES\r"
expect "YES\r"
expect {
   "YES" {
      send_user "found\n"
   }
   timeout {
      send_user "not found\n"
   }
}

Note how we need to do one expect for "YES\r" first to capture the echo back from the sent string. The second expect is looking for any output from the command. You could also do this with one expect looking for "YES\r\nYES"

1 Like

Thanks for your input. I tried your suggested code to check the presence of file and I can see the remote node throwing the following error and appears that usage "-f" option to check filename has got issues in send command.

invalid command name "-f"
    while executing
"-f  "
    invoked from within
"send "[ -f  ] && echo YES\r""

Hi.

My recollection is that TCL does command substitution when it encounters [ ... ] so perhaps a test command needs to be used within the brackets (which may look very strange to shell scriptors).

Best wishes ... cheers, drl

1 Like

Yes drl is correct and when I tested my script I had those square brackets escaped, but didn't past correctly you need:

expect "$ "
set fname /root/.ssh/authorized_keys
set timeout 2
send "\[ -f $fname \] && echo YES\r"
expect "YES\r"
expect {
   "YES" {
      send_user "found\n"
   }
   timeout {
      send_user "not found\n"
   }
}