服务器之间的数据复制传递
准备 Python 环境: 确保你的计算机上安装了 Python,并安装了 Paramiko 库。你可以使用
pip
命令来安装 Paramiko,如下所示:pip install paramiko
修改脚本: 将脚本中的以下变量替换为你的实际服务器信息和凭据:
source_server_ip
: 源服务器的 IP 地址或主机名。source_file
: 要复制的源文件的路径。source_dir
: 要复制的源文件夹的路径。destination_server_ip
: 目标服务器的 IP 地址或主机名。dest_path
: 目标服务器上的目标路径。username
: 登录服务器的用户名。password
: 登录服务器的密码。
运行脚本: 在命令行中运行脚本文件,如下所示:
python your_script.py
其中
your_script.py
是保存脚本代码的文件名。检查结果: 执行完脚本后,它将输出“File copied successfully!”和“Directory copied successfully!”,表示文件和文件夹已成功从源服务器复制到目标服务器。
import paramiko
import os
def copy_file(source_host, source_file, dest_host, dest_path, username, password):
# SSH 连接源服务器
source_ssh = paramiko.SSHClient()
source_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
source_ssh.connect(source_host, username=username, password=password)
# SCP 文件从源服务器复制到目标服务器
scp = paramiko.SFTPClient.from_transport(source_ssh.get_transport())
scp.get(source_file, os.path.join(dest_path, os.path.basename(source_file)))
# 关闭 SSH 连接
source_ssh.close()
def copy_directory(source_host, source_dir, dest_host, dest_path, username, password):
# SSH 连接源服务器
source_ssh = paramiko.SSHClient()
source_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
source_ssh.connect(source_host, username=username, password=password)
# 获取目录下所有文件和子目录
with source_ssh.open_sftp() as sftp:
for item in sftp.listdir(source_dir):
item_path = os.path.join(source_dir, item)
dest_item_path = os.path.join(dest_path, item)
if sftp.isfile(item_path): # 复制文件
sftp.get(item_path, dest_item_path)
elif sftp.isdir(item_path): # 递归复制子目录
os.makedirs(dest_item_path, exist_ok=True)
copy_directory(source_host, item_path, dest_host, dest_item_path, username, password)
# 关闭 SSH 连接
source_ssh.close()
def main():
# 源服务器和目标服务器的信息
source_host = 'source_server_ip'
source_file = '/path/to/source/file.txt'
source_dir = '/path/to/source/directory'
dest_host = 'destination_server_ip'
dest_path = '/path/to/destination/directory'
username = 'your_username'
password = 'your_password'
# 复制文件
copy_file(source_host, source_file, dest_host, dest_path, username, password)
print("File copied successfully!")
# 复制文件夹
copy_directory(source_host, source_dir, dest_host, dest_path, username, password)
print("Directory copied successfully!")
if __name__ == "__main__":
main()