import paramiko
import os
# 配置远程服务器信息
hostname = '192.168.101.130'
port = 22 # 默认SSH端口
username = 'root'
password = '123456'
def scp_upload_file(local_path, remote_path):
# 创建SSH客户端
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接到远程服务器
client.connect(hostname, port, username, password)
# 使用SCP协议上传文件
with client.open_sftp() as sftp:
sftp.put(local_path, remote_path)
print(f"文件 '{local_path}' 传输到远程服务器成功,存储为 '{remote_path}'")
except Exception as e:
print(f"文件传输失败: {str(e)}")
finally:
# 关闭SSH连接
client.close()
def scp_upload_folder(local_folder_path, remote_folder_path):
# 创建SSH客户端
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接到远程服务器
client.connect(hostname, port, username, password)
# 创建远程文件夹(如果不存在)
client.exec_command(f'mkdir -p {remote_folder_path}')
# 递归复制本地文件夹到远程服务器
with client.open_sftp() as sftp:
for foldername, subfolders, filenames in os.walk(local_folder_path):
for filename in filenames:
local_file_path = os.path.join(foldername, filename)
remote_file_path = os.path.join(
remote_folder_path, os.path.relpath(local_file_path, local_folder_path))
sftp.put(local_file_path, remote_file_path)
print(f"文件夹 '{local_folder_path}' 传输到远程服务器成功,存储为 '{remote_folder_path}'")
except Exception as e:
print(f"文件夹传输失败: {str(e)}")
finally:
# 关闭SSH连接
client.close()
# 例子:传输文件
local_file_path = 'test.py'
remote_file_path = '/www/wwwroot/python/test.py'
scp_upload_file(local_file_path, remote_file_path)
# 例子:传输文件夹
local_folder_path = './cache'
remote_folder_path = '/www/wwwroot/python/cache'
scp_upload_folder(local_folder_path, remote_folder_path)
python语言,实现本地文件传送到远程服务器
最新推荐文章于 2023-12-13 22:30:00 发布