Search code examples
bashsshscp

One password prompt for bash script including SCP and SSH


Printing documents from printer connected to internet is really slow at my university. Therefore I'm writing a script that sends a file to a remote computer with SCP, sends a series of commands over SSH to print the document from the remote computer (which has better connection with the printer) and then delete the file on the remote computer.

It works like a charm but the annoying part is that it prompts for the password two times, one time when it sends the file with SCP and one time when it sends commands over SSH. How can this be solved? I read that you can use a identity file? The thing is though that multiple users will use it and many has very limited experience with bash programming so the script must do everything including creating the file.

Users will mostly use Mac and the remote computer uses Red Hat. Here's the code so far:

    #!/bin/sh

    FILENAME="$1"
    PRINTER="$2"

    # checks if second argument is set, else prompt for it
    if [ -z ${PRINTER:+x} ]; then 
        printf "Printer: ";
        read PRINTER;
    fi

    # prompt for username
    printf "CID: "
    read CID

    scp $FILENAME $CID@adress:$FILENAME
    ssh -t $CID@adress bash -c "'
    lpr -P $PRINTER $FILENAME
    rm $FILENAME
    exit
    '"

Solution

  • You don't need to copy the file at all; you can simply send it to lpr via standard input.

    ssh -t $CID@adress lpr -P "$PRINTER" < "$FILENAME"
    

    (ssh reads from $FILENAME and forwards it to the remote command.)