Fredlo2010 Fredlo2010 - 2 months ago 26
Bash Question

Enter password automatically SSH

I am not a bash programmer, so the code I have is basically copy and paste from the web. I want to send a file to the server at school and print it from there because that's where the printers are hooked on.

Every time I print I get this error:

/usr/bin/expect: illegal option -- u
usage: expect [-div] [-c cmds] [[-f] cmdfile] [args]


This is the command I am trying to run :

cat test | ssh user@hostname.edu "lp -d printer123 -n 1 -"


and here is my full script:

#!/usr/bin/expect -f

# -u username
# -h host
# -p password
# -d destination printer where to print
# -n number of copies
# -f file to print

# I have the variables here so I can control some defaults
file_name="";
user="";
pass="";
host="hostname.edu";
destination="printer123";
copies=1;
cmd="";


# Collect the parameters
for ((i=1;i<=$#;i++));
do
if [ ${!i} = "-u" ]
then ((i++))
user=${!i};

elif [ ${!i} = "-h" ];
then ((i++))
host=${!i};

elif [ ${!i} = "-p" ];
then ((i++))
pass=${!i};

elif [ ${!i} = "-d" ];
then ((i++))
destination=${!i};

elif [ ${!i} = "-n" ];
then ((i++))
copies=${!i};

elif [ ${!i} = "-f" ];
then ((i++))
file_name=${!i};
fi
done;

#Prepare the command.
echo $cmd
cmd='cat '$file_name' | ssh '$user'@'$host' "lp -d '$destination' -n '$copies' -"';
echo $cmd

spawn $cmd;
expect "assword:"
send $pass"\r"
interact


Thanks

Answer

First: Look into key-based authentication. It's more secure, and easier to use once set up.

However, if you can't handle that or don't have the required access, you could use a tool like sshpass which automates password based authentication for you.

Your command should look something like the following once sshpass is installed:

cat test | sshpass -p PASSWORD ssh user@hostname.edu "lp -d printer123 -n 1 -"