python2写一个sftp现在脚本并输出日志到指定文本
时间: 2024-01-21 07:20:12 浏览: 115
以下是一个使用paramiko库编写的Python 2脚本,用于通过SFTP传输文件,并将日志输出到指定文本文件中:
```python
import paramiko
import logging
# 设置日志记录
logging.basicConfig(filename='sftp.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
# 定义SFTP传输函数
def sftp_transfer(host, port, username, password, local_file_path, remote_file_path):
try:
# 创建SSH客户端对象
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接SSH服务器
ssh.connect(host, port, username, password)
# 创建SFTP客户端对象
sftp = ssh.open_sftp()
# 上传本地文件到远程目录
sftp.put(local_file_path, remote_file_path)
# 关闭SFTP客户端
sftp.close()
# 记录成功日志
logging.info('SFTP transfer success: %s -> %s' % (local_file_path, remote_file_path))
except Exception as e:
# 记录失败日志
logging.error('SFTP transfer failed: %s' % e)
finally:
# 关闭SSH客户端
ssh.close()
# 示例调用
sftp_transfer('192.168.1.100', 22, 'user', 'password', '/path/to/local/file', '/path/to/remote/file')
```
在上面的示例中,我们使用了Python的logging模块来记录SFTP传输的成功和失败信息。你可以通过修改`filename`参数来指定日志文件的路径和名称。
阅读全文
相关推荐


















