Skip to content

Instantly share code, notes, and snippets.

@cstrahan
Last active May 5, 2017 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cstrahan/098f7bbda8470783f44765d016a17c6f to your computer and use it in GitHub Desktop.
Save cstrahan/098f7bbda8470783f44765d016a17c6f to your computer and use it in GitHub Desktop.
#!/bin/bash
# this is a little recipe for using `sudo rsync` on
# old machines that require a tty to call `sudo`.
#
# This prevents errors like:
#
# sudo: sorry, you must have a tty to run sudo
#
# when using rsync with sudo.
#
# For additional info, see:
# https://bugzilla.redhat.com/show_bug.cgi?id=1020147
# shell quote the given arguments.
function quote {
# quote each argument, interposing a space each time
local quoted="$(printf "%q " "$@")"
# nuke the trailing space
quoted="${quoted%?}"
printf "%s" "$quoted"
}
# use `script` to run the given command under a new tty.
function faketty {
if [[ "$(uname)" == "Darwin" ]]; then
script -q /dev/null "$@"
else
script -qefc "$(quote "$@")" /dev/null
fi
}
# the bash command to run in place of rsync on the remote host that
# proceeds as follows:
#
# 1) includes a copy of the `quote` and `faketty` definitions
# 2) leverages `script` to run `sudo rsync` under a pty
# 3) passes along the rsync server arguments ($@)
# 4) sets "rsync" as $0
SUDO_RSYNC_CMD="$(
quote "bash" "-c" "$(declare -f quote); $(declare -f faketty); faketty sudo rsync \"\$@\"" "rsync"
)"
rsync \
-e "ssh -qi $HOME/.ssh/some.key" \
--rsync-path "$SUDO_RSYNC_CMD" \
file.txt user@host:/dest/dir
@cstrahan
Copy link
Author

cstrahan commented May 2, 2017

The faketty stuff could possibly be avoided by passing -tt to ssh, so that it'll create a tty for us. The problem here is that many servers are configured to spew a bunch of noise from interactive shells, so by delaying the tty allocation until we're ready to call sudo, we avoid that trap.

Really, servers just shouldn't set Defaults requiretty and shouldn't spew a bunch of noise, but what can you do...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment