Advertisement
Guest User

Untitled

a guest
Feb 15th, 2017
187
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2.  
  3. set -e
  4.  
  5. function die() {
  6. echo "$@"
  7. exit 2
  8. }
  9.  
  10. OUTPUT_FILE="mtd_backup.tgz"
  11.  
  12. OPENWRT="ubnt@192.168.1.1"
  13.  
  14. TMPDIR=$(mktemp -d)
  15. BACKUP_DIR="$TMPDIR/mtd_backup"
  16. mkdir -p "$BACKUP_DIR"
  17. SSH_CONTROL="$TMPDIR/ssh_control"
  18.  
  19. function cleanup() {
  20. set +e
  21.  
  22. echo "Closing master SSH connection"
  23. "${SSH_CMD[@]}" -O stop
  24.  
  25. echo "Removing temporary backup files"
  26. rm -r "$TMPDIR"
  27. }
  28. trap cleanup EXIT
  29.  
  30. # Open master ssh connection, to avoid the need to authenticate multiple times
  31. echo "Opening master SSH connection"
  32. ssh -oControlMaster=yes -oControlPath="$SSH_CONTROL" -o ControlPersist=10 -n -N "$OPENWRT"
  33.  
  34. # This is the command we'll use to reuse the master connection
  35. SSH_CMD=(ssh -oControlMaster=no -oControlPath="$SSH_CONTROL" -n "$OPENWRT")
  36.  
  37. # List remote mtd devices from /proc/mtd. The first line is just a table
  38. # header, so skip it (using tail)
  39. "${SSH_CMD[@]}" 'cat /proc/mtd' | tail -n+2 | while read; do
  40. MTD_DEV=$(echo $REPLY | cut -f1 -d:)
  41. MTD_NAME=$(echo $REPLY | cut -f2 -d\")
  42. echo "Backing up $MTD_DEV ($MTD_NAME)"
  43. # It's important that the remote command only prints the actual file
  44. # contents to stdout, otherwise our backup files will be corrupted. Other
  45. # info must be printed to stderr instead. Luckily, this is how the dd
  46. # command already behaves by default, so no additional flags are needed.
  47. "${SSH_CMD[@]}" "sudo dd if='/dev/${MTD_DEV}ro'" > "${BACKUP_DIR}/${MTD_DEV}_${MTD_NAME}.backup" || die "dd failed, aborting..."
  48. done
  49.  
  50. # Use gzip and tar to compress the backup files
  51. echo "Compressing backup files to \"$OUTPUT_FILE\""
  52. (cd "$TMPDIR" && tar czf - "$(basename "$BACKUP_DIR")") > "$OUTPUT_FILE" || die 'tar failed, aborting...'
  53.  
  54. # Clean up a little earlier, so the completion message is the last thing the user sees
  55. cleanup
  56. # Reset signal handler
  57. trap EXIT
  58.  
  59. echo -e "\nMTD backup complete. Extract the files using:\ntar xzf \"$OUTPUT_FILE\""
Advertisement
RAW Paste Data Copied
Advertisement