通过Python Paramiko

时间:2018-04-26 06:11:01

标签: python ssh sftp paramiko su

我希望使用服务帐户连接到我的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

1 个答案:

答案 0 :(得分:0)

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

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

无论如何,open_sftp_clientexec_command在两个不同的SSH频道上运行。因此,您的代码无法正常工作,因为sftp在非提升会话上运行,而且根本不受exec_command的影响。

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

您必须实施SFTPClient.from_transport替代exec_command而非invoke_subsystem的替代方案。