通过Python Paramiko以不同的用户身份运行SFTP操作

问题描述 投票:1回答:1

我想使用服务帐户连接到我的Ubuntu服务器,但代表另一个用户执行文件传输操作。我的sshd_config有以下内容(以及其他内容):

PubKeyAuthentication yes
PasswordAuthentication yes
Subsystem sftp /usr/lib/openssh/sftp-server

我尝试了以下代码但没有任何成功:

t = paramiko.Transport(('<address>', <port>))  
t.connect(username='serviceAccount', password='<password>')
channel = t.open_session()
channel.exec_command('sudo su -l <other user> -c /usr/lib/openssh/sftp-server')
sftp = t.open_sftp_client()
file = sftp.file("<some path>", "w", bufsize=...)
file.write(...)
file.close()
sftp.close()
channel.close()
t.close()

这是我在运行此代码时看到的错误:

IOError: [Errno 13] Permission denied
python ssh sftp paramiko su
1个回答
0
投票

首先,自动化susudo不是正确的解决方案。

正确的解决方案是直接使用您需要使用的帐户登录。


无论如何,open_sftp_clientexec_command在两个不同的SSH频道上运行。所以你的代码无法工作,因为sftp在非高架会话上运行,它根本不受exec_command的影响。

在Paramiko中没有明确支持使用su运行SFTP(因为这种方法是错误的,很难标准化)。

你必须实现SFTPClient.from_transport的替代方案,它将调用你的exec_command而不是invoke_subsystem

© www.soinside.com 2019 - 2024. All rights reserved.