Python发送文件给sftp服务器
时间: 2024-02-16 17:22:25 浏览: 118
要使用Python发送文件到SFTP服务器,可以使用paramiko库。以下是一个简单的示例代码:
```python
import paramiko
def send_file_to_sftp(local_file_path, remote_file_path, hostname, username, password, port=22):
# 创建SSH客户端
ssh_client = paramiko.SSHClient()
# 自动添加主机密钥
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接SFTP服务器
ssh_client.connect(hostname, port, username, password)
# 创建SFTP客户端
sftp_client = ssh_client.open_sftp()
# 上传本地文件到远程路径
sftp_client.put(local_file_path, remote_file_path)
# 关闭SFTP客户端和SSH客户端连接
sftp_client.close()
ssh_client.close()
# 示例用法
local_file_path = '/path/to/local/file.txt'
remote_file_path = '/path/to/remote/file.txt'
hostname = 'sftp.example.com'
username = 'sftp_username'
password = 'sftp_password'
send_file_to_sftp(local_file_path, remote_file_path, hostname, username, password)
```
在上面的示例中,您需要将`local_file_path`替换为本地文件的路径,`remote_file_path`替换为要上传到的SFTP服务器上的远程路径,`hostname`替换为SFTP服务器的主机名或IP地址,`username`和`password`替换为SFTP服务器的登录凭证。
请注意,paramiko库需要事先安装,可以使用pip进行安装:`pip install paramiko`。
阅读全文
相关推荐


















