Python 备份 CentOS 服务器项目和数据库到本地

import paramiko
import time

paths = '/.../.../...'
backup_paths = ('/.../.../.../templates/', '/.../.../.../static/images/', '/.../.../.../blog.sql')
file_name = 'all_{}'.format(time.strftime('%Y%m%d',time.localtime()))
mysql_command = 'mysqldump -u root -p 数据库名称 > blog.sql'
tar_command = 'tar -cf {}.tar {}'.format(file_name, ' '.join(backup_paths))
commands = ['cd {}'.format(paths), mysql_command]

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname='IP', username='username', password='password')
stdin, stdout, stderr = ssh_client.exec_command(' \n '.join(commands))

stdin.write('数据库password\n')

# stdin 只写操作,可用于命令的输入
# stdout 命令结果的输出
# stderr 执行命令的错误信息, 没有则返回空

commands[-1] = tar_command
stdin, stdout, stderr = ssh_client.exec_command(' \n '.join(commands))

# linux 下载文件到 Windows
ftp_client = ssh_client.open_sftp()
ftp_client.get('{}/{}.tar'.format(paths, file_name), r'E:\centos\blog_backup\{}.tar'.format(file_name))
ftp_client.close()

print('end...')
ssh_client.close()

展开阅读全文