问题描述
无法使 pysftp.connection.cd()
正常工作 - 不确定我做错了什么或问题是什么。我可以通过将完整的远程路径传递给相关方法来实现我所需要的。但是如果尝试更改远程活动目录,我会收到错误消息。相关代码如下:
with ps.Connection('hostname or IP address',username='username',password='secret',cnopts=cnopts) as conn:
print("Connection successful....")
print(conn.listdir()) # this works
print(conn.listdir(remote_location)) # this works
with conn.cd(remote_location): # this throws an error
print(conn.listdir())
我得到的错误如下:
File "C:\Users\username\.conda\envs\data_wrangling\lib\site-packages\pysftp\__init__.py",line 508,in cd
self.cwd(remotepath)
File "C:\Users\username\.conda\envs\data_wrangling\lib\site-packages\pysftp\__init__.py",line 524,in chdir
self._sftp.chdir(remotepath)
File "C:\Users\username\.conda\envs\data_wrangling\lib\site-packages\paramiko\sftp_client.py",line 659,in chdir
if not stat.S_ISDIR(self.stat(path).st_mode):
OverflowError: mode out of range
During handling of the above exception,another exception occurred:
Traceback (most recent call last):
File "c:\Users\username\my_code\python\mears_to_er_interface\sftp_chdir_test.py",line 41,in <module>
with conn.cd("remote_location"):
File "C:\Users\username\.conda\envs\data_wrangling\lib\contextlib.py",line 112,in __enter__
return next(self.gen)
File "C:\Users\username\.conda\envs\data_wrangling\lib\site-packages\pysftp\__init__.py",line 511,in cd
self.cwd(original_path)
File "C:\Users\username\.conda\envs\data_wrangling\lib\site-packages\pysftp\__init__.py",in chdir
if not stat.S_ISDIR(self.stat(path).st_mode):
OverflowError: mode out of range
conn.stat(remote_location).st_mode
的输出是 83448
。
解决方法
Paramiko 在 SFTPClient.chdir
实现中使用 Python stat
模块来检查路径是否是文件夹(而不是文件)。
问题是 Python stat
模块只能使用 16 位权限。您的 SFTP 服务器返回第 17 位设置的权限。这导致 OverflowError
。
你无能为力。请参阅此 Python 问题:stat.S_ISXXX can raise OverflowError for remote file modes。
尽量避免使用 SFTPClient.chdir
。只需在 Paramiko API 中随处使用绝对路径,而不是依赖相对于使用 chdir
设置的工作目录的路径。
Paramiko 当前使用 stat
模块的唯一其他地方是 SFTPAttributes.__str__
。否则你应该是安全的。
我已将此事报告给 Paramiko 项目:https://github.com/paramiko/paramiko/issues/1802