Linux: ssh command works outside bash script, but not within script?

0

I am having problem with the following command:

echo "Pass for router:"
read -s pass

/usr/bin/expect - << EXPCT
spawn ssh 192.168.10.1 -l root 'opkg list-installed' > list-installed.txt
#echo @pass
expect -timeout 10000 "password: "
send -- "$pass\n";
expect "#"
interact
EXPCT

this returns:

Pass for router:
spawn ssh 192.168.10.1 -l root 'opkg list-installed' > list-installed.txt
root@192.168.10.1's password: 
ash: opkg list-installed: not found
spawn_id: spawn id exp6 not open
    while executing
"interact"

problem is that when I use a manual:

ssh 192.168.10.1 -l root 'opkg list-installed' > list-installed.txt

it works flawlessly. Some other points:

'opkg list-installed' > list-installed.txt

doing it that way it successfuly run the command opkg list-installed in the REMOTE machine and saves the result in the LOCAL machine. it's the only way that it works like that. If I login with SSH and then try to do that command it doesn't work, or if it works it saves in the remote path.

FernandoSBS

Posted 2013-11-17T18:05:57.050

Reputation: 1 541

Answers

0

For something like this, your should try SSH Pass or using SSH-Keys. This would solve your issue with expect (which is like a Hammer for this kind of stuff).

This way, you just issue your standard ssh command :

sshpass -p $pass ssh root@192.168.10.1 'opkg list-installed' > list-installed.txt

Adrien M.

Posted 2013-11-17T18:05:57.050

Reputation: 199

yes this works. I was trying to avoid having to install sshpass, but after a lot of time lost I believe it's the way to go. – FernandoSBS – 2013-11-17T19:24:35.677

0

try it this way, firdt connect then run command on remote. not direct pass the commend on connection.

echo "Pass for router:"
read -s pass

/usr/bin/expect - << EXPCT
spawn ssh 192.168.10.1 -l root
opkg list-installed > list-installed.txt
#echo @pass
expect -timeout 10000 "password: "
send -- "$pass\n";
expect "#"
interact
EXPCT

konqui

Posted 2013-11-17T18:05:57.050

Reputation: 504

doesn't work. probably because: If I login with SSH and then try to do that command it doesn't work, or if it works it saves in the remote path. – FernandoSBS – 2013-11-17T19:23:01.280

0

Something that bites me again and again: leaving the -n option off ssh while looping across a list of hostnames on stdin

sshopts="-o StrictHostKeyChecking=no -o ConnectTimeout=5 "
sshopts+=" -n" # keep it from swallowing stdin

while read remotehostname; do
    sshpass [...] ssh ${sshopts} [...]
done < ${HOSTFILE}

[Insert standard editorial on why sshpass is inherently insecure unless you interactively prompt for the SSHPASS variable and all competent sysadmins should throw a hissy fit until their local security guidelines allow passwordless access via ssh keys.]

arp

Posted 2013-11-17T18:05:57.050

Reputation: 101