使用 Python 中的paramiko库实现通过 SSH 在两台服务器之间进行数据传输的示例代码:
import paramiko
# 源服务器信息
source_host = 'source_server_ip'
source_username = 'source_username'
source_password = 'source_password'
source_path = '/path/to/source/file'
# 目标服务器信息
target_host = 'target_server_ip'
target_username = 'target_username'
target_password = 'target_password'
target_path = '/path/to/destination/file'
def transfer_data():
# 创建 SSH 客户端对象
client = paramiko.SSHClient()
# 自动添加主机到已知主机列表
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接源服务器
client.connect(source_host, username=source_username, password=source_password)
# 连接目标服务器
client.connect(target_host, username=target_username, password=target_password)
# 打开源文件和目标文件
with client.open_sftp() as sftp:
source_file = sftp.open(source_path, 'rb')
target_file = sftp.open(target_path, 'wb')
# 读取源文件内容并写入目标文件
data = source_file.read()
target_file.write(data)
print(f"数据从 {source_path} 成功传输到 {target_path}")
except Exception as e:
print(f"传输过程中出现错误:{e}")
finally:
# 关闭连接
client.close()
if __name__ == '__main__':
transfer_data()
上述代码假设源服务器和目标服务器都支持 SSH 连接,并且你有相应的用户名和密码。
如果服务器使用密钥进行身份验证,可以使用paramiko的密钥相关方法来替代密码验证部分。
如果要在本地和服务器之间传输数据,可以使用scp模块来实现类似的功能:
import scp
# 服务器信息
host = 'server_ip'
username = 'username'
password = 'password'
remote_path = '/path/to/remote/file'
local_path = '/path/to/local/file'
def transfer_data():
client = scp.SCPClient(host, username=username, password=password)
try:
# 从服务器下载文件到本地
client.get(remote_path, local_path)
# 或者将本地文件上传到服务器
client.put(local_path, remote_path)
print(f"数据传输成功")
except Exception as e:
print(f"传输过程中出现错误:{e}")
finally:
client.close()
if __name__ == '__main__':
transfer_data()
使用密码进行连接可能存在安全风险,在实际应用中可以考虑使用密钥对或其他更安全的身份验证方式。