Last active
July 11, 2019 09:59
-
-
Save manzanit0/7e8f01d6f43ee2fb264c878cf37ecd28 to your computer and use it in GitHub Desktop.
Create remote DB backup via SSH
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from paramiko import SSHClient, RSAKey, AutoAddPolicy | |
import sys, argparse, time | |
def ssh_connect(host, user, key): | |
ssh = SSHClient() | |
ssh.load_system_host_keys() | |
ssh.set_missing_host_key_policy(AutoAddPolicy()) | |
pkey = RSAKey.from_private_key_file(key) | |
ssh.connect(hostname=host, username=user, pkey=pkey) | |
print('Connected to server succesfully!') | |
return ssh | |
def print_stream(stream): | |
for line in iter(stream.readline, ""): | |
print(line, end="") | |
def execute_command(ssh, command, inputt=""): | |
stdin, stdout, stderr = ssh.exec_command(command) | |
stdin.write(inputt) | |
print_stream(stdout) | |
print_stream(stderr) | |
stdin.flush() | |
def print_progress(transferred, to_be_transferred): | |
percentage = '%.2f'%((transferred / to_be_transferred) * 100) | |
print("Transferred: {0}%".format(percentage)) | |
time.sleep(1) | |
def transfer_file(ssh, remote, local): | |
sftp = ssh.open_sftp() | |
sftp.get(remote, local, callback=print_progress) | |
def setup_cli_parser(): | |
text = 'This script connects to a remote AWS EC2 instance, creates a MySQL dump and transfers it to the local machine' | |
parser = argparse.ArgumentParser(description = text) | |
parser.add_argument("-hh", "--ssh-host", required=True) | |
parser.add_argument("-kk", "--ssh-key", required=True) | |
parser.add_argument("-dh", "--db-host", required=True) | |
parser.add_argument("-dn", "--db-name", required=True) | |
parser.add_argument("-du", "--db-user", required=True) | |
parser.add_argument("-dp", "--db-password", required=True) | |
parser.add_argument("-l", "--local-directory", required=True) | |
return parser | |
### START OF SCRIPT | |
parser = setup_cli_parser() | |
args = parser.parse_args() | |
ssh = None | |
try: | |
ssh = ssh_connect(host=args.ssh_host, user="ec2-user", key=args.ssh_key) | |
execute_command(ssh, "sudo yum install mysql-server", "y\n") | |
c = "mysqldump --databases " + args.db_name + " -h " + args.db_host + " -u " + args.db_user + " -p" + args.db_password + "> dump.sql" | |
execute_command(ssh, c) | |
transfer_file(ssh, "/home/ec2-user/dump.sql", args.local_directory + "dump.sql") | |
finally: | |
if ssh: | |
ssh.close() | |
print("Backup completed and connection closed!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment