import paramiko
import os

# Remote server details
hostname = 'demo.gcreate.com.tw'
username = 'root'
password = 'Remember#@!~'

# Local directory to save the files
local_dir = '/var/www/html/kuma_test'

# Connect to remote server using SSH
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=hostname, username=username, password=password)



# Open an SCP channel to transfer files
scp = client.open_sftp()

# List all files and directories in /var/www/html
remote_dir = '/var/www/html/kumatest'
files = scp.listdir(remote_dir)

# Recursively copy all files and directories from /var/www/html to local_dir
for file in files:
    remote_file = os.path.join(remote_dir, file)
    local_file = os.path.join(local_dir, file)
    if scp.stat(remote_file).st_mode & 0o40000:
        # Directory
        os.makedirs(local_file, exist_ok=True)
        for subfile in scp.listdir(remote_file):
            sub_remote_file = os.path.join(remote_file, subfile)
            sub_local_file = os.path.join(local_file, subfile)
            scp.get(sub_remote_file, sub_local_file)
    else:
        # File
        scp.get(remote_file, local_file)

# Close the SCP channel and SSH connection
scp.close()
client.close()

print('All files and directories from /var/www/html have been copied to', local_dir)

