Copy folder from server(Linux) to local machine(windows) in python

  • 8 months ago
Comment

ChatGPT
1 / 1

You can use the paramiko library in Python to establish an SSH connection to the Linux server and then use the sftp module to copy files and folders from the server to your local Windows machine. Here's an example of how to do this:

  1. Install the paramiko library if you haven't already:
pip install paramiko
  1. Create a Python script to copy the folder:
python
import paramiko
import os

# Server details
server_ip = 'your_server_ip'
server_port = 22
username = 'your_username'
password = 'your_password'

# Source and destination paths
source_path = '/path/to/source/folder'
destination_path = 'C:\\path\\to\\destination\\folder'

# Create an SSH client
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to the server
client.connect(server_ip, server_port, username=username, password=password)

# Create an SFTP session
sftp = client.open_sftp()

# Copy files and folders recursively
for root, dirs, files in sftp.walk(source_path):
for file in files:
remote_file_path = os.path.join(root, file)
local_file_path = os.path.join(destination_path, remote_file_path[len(source_path):])
os.makedirs(os.path.dirname(local_file_path), exist_ok=True)
sftp.get(remote_file_path, local_file_path)
print(f"Downloaded: {remote_file_path} -> {local_file_path}")

# Close the SFTP session and the SSH connection
sftp.close()
client.close()

print("Copy completed.")

Replace your_server_ip, your_username, your_password, /path/to/source/folder, and C:\\path\\to\\destination\\folder with your actual server and path details.

Run the script on your local Windows machine. It will connect to the Linux server, copy the specified folder and its contents recursively, and save them to the specified destination path on your Windows machine.