Python Script To Copy Files From One Server To Another

Migrating files across servers can be a tedious manual chore. But fear not, fellow data wranglers! Python, the versatile programming language, comes to the rescue with its powerful file transfer capabilities. Let's craft a simple script that whisks your data away to its new home, freeing you for more exciting tasks.

Code Explained:

Python
import paramiko

# Define server details
server1_ip = "192.168.1.10"
server1_username = "user1"
server1_password = "secure_password"
server1_file_path = "/path/to/source_file.txt"

server2_ip = "10.0.0.1"
server2_username = "user2"
server2_password = "another_secure_password"
server2_destination = "/path/to/destination_folder"

# Establish SSH connection
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=server1_ip, username=server1_username, password=server1_password)

# Open source and destination files
sftp_client = ssh_client.open_sftp()
source_file = sftp_client.open(server1_file_path, "rb")
destination_file = sftp_client.open(f"{server2_destination}/{source_file.name}", "wb")

# Transfer data in chunks
data = source_file.read(1024)
while data:
    destination_file.write(data)
    data = source_file.read(1024)

# Close files and connection
source_file.close()
destination_file.close()
sftp_client.close()
ssh_client.close()

print("File successfully transferred!")

Applications:

This script can be used for various scenarios:

  • Automated backups: Regularly copy critical data from one server to another for safekeeping.
  • Data migration: Move large datasets between servers efficiently.
  • Continuous deployment: Automatically transfer application files to production servers after updates.

Conclusion:

With a few lines of Python, you can automate file transfers between servers, saving time and effort. This script is just a starting point; customize it to fit your specific needs and watch your data fly! Remember, the possibilities are endless with Python as your programming ally.

Post a Comment

0 Comments