sshpaste (2865B)
- #!/bin/sh
- # Copyright 2018 Haelwenn (lanodan) Monnier <contact@hacktivis.me>
- # Distributed under the terms of the ISC license
- datetime="$(date -u +%FT%T)"
- target_ssh="cloudsdale.hacktivis.me:pastes/${datetime}"
- target_www="https://cloudsdale.hacktivis.me/pastes/${datetime}"
- die() {
- if [ -n "$*" ]
- then echo "${*}, exiting…" >&2
- else echo "Failed, exiting…" >&2
- fi
- if [ -e "${temporary_file}" ]
- then
- rm -f "${temporary_file}"
- fi
- exit
- }
- sshpaste_file() {
- [ -s "$1" ] || die "$1 is empty"
- target_name=$(basename "$1")
- chmod +r "$1"
- file -i "$1" 2>/dev/null | grep 'text/' && target_name="${target_name}.txt"
- if scp -q "$1" "${target_ssh}-'${target_name}'"
- then echo "${target_www}-${target_name}"
- else die "Failed uploading $1"
- fi
- }
- sshpaste_xclip() {
- temporary_file="$(mktemp -t sshpaste_xclip.XXXXXXXX)"
- xclip -o > "${temporary_file}" || die "xclip output"
- sshpaste_file "${temporary_file}"
- rm -f "${temporary_file}"
- }
- sshpaste_command() {
- temporary_file="$(mktemp -t sshpaste_command.XXXXXXXX)"
- sh -x -c "$*" > "${temporary_file}" 2>&1
- #echo "${PS4}$*" > "${temporary_file}"
- #sh -c "$*" >> "${temporary_file}" 2>&1
- sshpaste_file "${temporary_file}"
- rm -f "${temporary_file}"
- }
- sshpaste_stdin() {
- temporary_file="$(mktemp -t sshpaste_stdin.XXXXXXXX)"
- tty 2&1 >/dev/null && echo "Reading from stdin, press EOF(^D) when you're done"
- cat - > "${temporary_file}" || die "reading from stdin"
- sshpaste_file "${temporary_file}"
- rm -fr ${temporary_file}
- }
- sshpaste_usage() {
- cat >&2 <<EOF
- Usage: ${1} [options] [file(s)]
- Options:
- -c COMMAND paste COMMAND and the output of COMMAND
- Can be used only once, not compatible with -x
- -h show this help
- -x read input from clipboard (requires xclip)
- Can be used only once, not compatible with -c
- When no options or files are given, ${1} reads from stdin, it assumes plain text is given and so puts a .txt extension
- EOF
- }
- flag_x=
- flag_c=
- temporary_file=
- while getopts "xhc:" opt
- do
- case $opt in
- 'c')
- [ ! -z $flag_x ] && die "Cannot have both -x and -c"
- [ ! -z $flag_c ] && die "Cannot have two -c, use ; if you want multiple commands"
- flag_c=1
- opt_command="${OPTARG}"
- ;;
- 'h')
- sshpaste_usage $0
- exit 0
- ;;
- 'x')
- [ ! -z $flag_c ] && die "Cannot have both -x and -c"
- flag_x=1
- ;;
- '?')
- sshpaste_usage $0
- exit 2
- ;;
- ':')
- echo "Option -${OPTARG} requires an argument, exiting…" >&2
- exit 1
- ;;
- esac
- done
- if [ ! -z "${flag_x}" ]
- then
- sshpaste_xclip
- elif [ ! -z "${opt_command}" ]
- then
- sshpaste_command ${opt_command}
- elif [ "$#" -eq 0 ]
- then
- sshpaste_stdin
- else
- # try to upload the rest of the arguments if they are files
- shift $(($OPTIND - 1))
- for file in "$@"
- do test -n "$file"
- if [ "$file" == '-' ]
- then sshpaste_stdin
- else sshpaste_file "$file"
- fi
- done
- fi