Unable to check if file exists on remote server using expect

Hi,

I need to check if a file exists on remote server using expect.

#!/bin/bash
ip_addr=10.10.10.10
user=root
passwd=Help
filename=/root/test
expect -c "
spawn ssh -n -T -o NumberOfPasswordPrompts=3 -o StrictHostKeyChecking=no $user@$ip_addr
expect \"*?assword:*\"
send -- \"$passwd\r\"
expect {
\"ls $filename\" { exp_continue }
$filename { puts found }
timeout { puts \"timed out\" }
}
"

The above code is not working. I need to capture the output and if file does not exist, i need to perform some steps. Any other approach using expect only will be appreciated as I cannot do key sharing.
Please help.

I have not used expect so much, but may be you can pass in the ls command in the ssh itself, like so

spawn ssh ..... "ls $filename"

I have come across similar situations before, but in my case, I have always been able to add the public key to the remote host so i dont need password, and then I simply

ssh hostname ls $file
if [ $? -ne 0 ]; then
  echo "handle missing file here"
fi

Thank you linuxpenguin, but i need to do it via expect only, as my task does not allow key sharing.So i have to send the password via expect only.

I was able to solve the issue.Please find below the code

#/bin/bash

ip_addr=10.10.10.10.
user=root
passwd=Help
filename=test_backup.sh
path=/root/


VAR=$(expect -c "
                    spawn ssh -n -T -o NumberOfPasswordPrompts=3 -o StrictHostKeyChecking=no $user@$ip_addr \"ls $path/$filename\"
                    expect \"*?assword:*\"
                    send -- \"$passwd\r\"
                    expect {
                        \"$path/$filename\" {
                        exit 0
                        }
                        \"ls: $path/$filename: No such file or directory\" {
                        exit 1
                        }
                    }
                    expect eof
                    ")
                echo "$VAR" | grep -q -e "No such file"
                if [ $? -eq 0 ];then
                VAR=$(expect -c 2> /dev/null "
                        spawn scp -q -o NumberOfPasswordPrompts=3 -o StrictHostKeyChecking=no $path/$filename $user@$ip_addr:$path
                        expect \"*?assword:*\"
                        send -- \"$passwd\r\"
                        send -- \"\r\"
                        expect eof
                        ")
                else
                    echo "$filename already exists at ip address $ip_addr at path $path"
                fi

1 Like

Thanks for the update!

If your administrator does not allow you to use keys for security reasons, they will be livid to discover you getting around this limitation with an insecure third-party brute forcing tool.

1 Like

@Corona688 I understand the point you are making, but then as of now, this has to be implemented like this only. After some time, they will move to key sharing..