๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป๊ฐœ๋ฐœ

[Python] ์„œ๋ฒ„์˜ MySQL ํ…Œ์ด๋ธ”์„ 1์‹œ๊ฐ„๋งˆ๋‹ค dumpํ•˜๊ณ  ๋กœ์ปฌ๋กœ ๋ฐฑ์—…ํ•˜๋Š” ์ฝ”๋“œ

by ๋ˆˆ๋ˆ„ :) 2023. 3. 29.

 

 

 

Python์˜ Paramiko๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์„œ๋ฒ„์— ์•ก์„ธ์Šค ํ•˜์—ฌ ์„œ๋ฒ„์˜ MySQL ํŠน์ • ํ…Œ์ด๋ธ”์„ dumpํ•ด์„œ ํŒŒ์ผ์„ PC๋กœ์ปฌ๋กœ ๊ฐ€์ ธ์˜ค๋Š” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.

 

 

 

import paramiko
import os
import time

# ์„œ๋ฒ„ ์ ‘์† ์ •๋ณด
hostname = 'your_server_ip'
port = 22
username = 'your_username'
password = 'your_password'

# MySQL ์ •๋ณด
mysql_user = 'your_mysql_user'
mysql_password = 'your_mysql_password'
mysql_database = 'your_database'
mysql_table = 'your_table'

# ๋กœ์ปฌ ํŒŒ์ผ ๊ฒฝ๋กœ
local_file_path = os.path.join(os.getcwd(), f'{mysql_table}.sql')

# SSH ํด๋ผ์ด์–ธํŠธ ์ƒ์„ฑ ๋ฐ ์—ฐ๊ฒฐ
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, port, username, password)

# 24์‹œ๊ฐ„ ๋™์•ˆ 1์‹œ๊ฐ„๋งˆ๋‹ค ๋คํ”„ ๋ฐ ์ „์†ก
for i in range(24):
    # MySQL ๋คํ”„ ๋ช…๋ น์–ด ์‹คํ–‰
    dump_cmd = f'mysqldump -u {mysql_user} -p{mysql_password} {mysql_database} {mysql_table} > /tmp/{mysql_table}.sql'
    stdin, stdout, stderr = ssh.exec_command(dump_cmd)
    stdout.channel.recv_exit_status()

    # SFTP ํด๋ผ์ด์–ธํŠธ ์ƒ์„ฑ ๋ฐ ํŒŒ์ผ ์ „์†ก
    sftp = ssh.open_sftp()
    sftp.get(f'/tmp/{mysql_table}.sql', local_file_path)
    sftp.close()

    # 1์‹œ๊ฐ„ ๋Œ€๊ธฐ
    time.sleep(3600)

# SSH ์—ฐ๊ฒฐ ์ข…๋ฃŒ
ssh.close()

 

 

 

์ด ์ฝ”๋“œ๋Š” ์„œ๋ฒ„์— SSH๋กœ ์ ‘์†ํ•˜์—ฌ MySQL ๋คํ”„ ๋ช…๋ น์–ด๋ฅผ ์‹คํ–‰ํ•˜๊ณ , ์ƒ์„ฑ๋œ ๋คํ”„ ํŒŒ์ผ์„ SFTP๋ฅผ ํ†ตํ•ด ๋กœ์ปฌ ์ปดํ“จํ„ฐ๋กœ ์ „์†กํ•ฉ๋‹ˆ๋‹ค.

 

 

์ด ์ฝ”๋“œ๋Š” Python์˜ paramiko ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์„œ๋ฒ„์— SSH๋กœ ์ ‘์†ํ•˜๊ณ ,

MySQL ๋คํ”„ ๋ช…๋ น์–ด๋ฅผ ์‹คํ–‰ํ•˜์—ฌ ํŠน์ • ํ…Œ์ด๋ธ”์„ ๋คํ”„ํ•œ ๋‹ค์Œ,

์ƒ์„ฑ๋œ ๋คํ”„ ํŒŒ์ผ์„ SFTP๋ฅผ ํ†ตํ•ด ๋กœ์ปฌ ์ปดํ“จํ„ฐ๋กœ ์ „์†กํ•˜๋Š” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.

์ด ์ฝ”๋“œ๋Š” 24์‹œ๊ฐ„ ๋™์•ˆ 1์‹œ๊ฐ„๋งˆ๋‹ค ๋ฐ˜๋ณตํ•˜์—ฌ ๋คํ”„ ๋ฐ ์ „์†ก ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

 

 

์ฝ”๋“œ์˜ ์ƒ๋‹จ์—๋Š” ์„œ๋ฒ„ ์ ‘์† ์ •๋ณด์™€ MySQL ์ •๋ณด๊ฐ€ ์ •์˜๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.

์ด ์ •๋ณด๋“ค์€ ์‚ฌ์šฉ์ž์˜ ์„œ๋ฒ„ ํ™˜๊ฒฝ์— ๋งž๊ฒŒ ์ˆ˜์ •ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

๊ทธ ๋‹ค์Œ์œผ๋กœ paramiko.SSHClient ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  connect ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์„œ๋ฒ„์— SSH๋กœ ์ ‘์†ํ•ฉ๋‹ˆ๋‹ค.

 


๊ทธ ๋‹ค์Œ์œผ๋กœ for ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ 24๋ฒˆ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.

๊ฐ ๋ฐ˜๋ณต์—์„œ๋Š” exec_command ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ MySQL ๋คํ”„ ๋ช…๋ น์–ด๋ฅผ ์‹คํ–‰ํ•˜๊ณ ,

open_sftp ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ SFTP ํด๋ผ์ด์–ธํŠธ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•œ ๋‹ค์Œ,

get ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ƒ์„ฑ๋œ ๋คํ”„ ํŒŒ์ผ์„ ๋กœ์ปฌ ์ปดํ“จํ„ฐ๋กœ ์ „์†กํ•ฉ๋‹ˆ๋‹ค.

๊ฐ ๋ฐ˜๋ณต ์‚ฌ์ด์— time.sleep(3600)์„ ์‚ฌ์šฉํ•˜์—ฌ 1์‹œ๊ฐ„ ๋™์•ˆ ๋Œ€๊ธฐํ•ฉ๋‹ˆ๋‹ค.

 


๋งˆ์ง€๋ง‰์œผ๋กœ close ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ SSH ์—ฐ๊ฒฐ์„ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.