How can I scp a file and run an ssh command asking for password only once?
ssh user@host 'cat - > /tmp/file.ext; do_something_with /tmp/file.ext;rm /tmp/file.ext' < file.ext
Another option would be to just leave an ssh tunnel open:
In ~/.ssh/config:
Host * ControlMaster auto ControlPath ~/.ssh/sockets/ssh-socket-%r-%h-%p
.
$ ssh -f -N -l user host(socket is now open)
Subsequent ssh/scp requests will reuse the already existing tunnel.
Here is bash script template, which follows @Wrikken's second method, but can be used as is - no need to edit user's SSH config file:
#!/bin/bashTARGET_ADDRESS=$1 # the first script argumentHOST_PATH=$2 # the second script argumentTARGET_USER=rootTMP_DIR=$(mktemp -d)SSH_CFG=$TMP_DIR/ssh-cfgSSH_SOCKET=$TMP_DIR/ssh-socketTARGET_PATH=/tmp/file# Create a temporary SSH config file:cat > "$SSH_CFG" <<ENDCFGHost * ControlMaster auto ControlPath $SSH_SOCKETENDCFG# Open a SSH tunnel:ssh -F "$SSH_CFG" -f -N -l $TARGET_USER $TARGET_ADDRESS# Upload the file:scp -F "$SSH_CFG" "$HOST_PATH" $TARGET_USER@$TARGET_ADDRESS:"$TARGET_PATH"# Run SSH commands:ssh -F "$SSH_CFG" $TARGET_USER@$TARGET_ADDRESS -T <<ENDSSH# Do something with $TARGET_PATH hereENDSSH# Close the SSH tunnel:ssh -F "$SSH_CFG" -S "$SSH_SOCKET" -O exit "$TARGET_ADDRESS"