4

Using the standard client.open_sftp() handle gives me SFTP controls but without sudo/root permissions, any sort of /etc/** files can't be edited. I have a user that has passwordless sudo access, I figured I could maybe start off with sudo su and then invoke SFTP but that did not seem to be the case.

t = paramiko.Transport(('192.168.56.102', 22))  
t.connect(username='vagrant', password='vagrant')
chan = t.open_session()
chan.get_pty()
chan.invoke_subsystem('sftp')
chan.exec_command('sudo su')
sftp = paramiko.SFTPClient.from_transport(t)

.. the error

paramiko.ssh_exception.SSHException: Channel closed.
DEBUG:paramiko.transport:EOF in transport thread

Any tips how to get Paramiko to open SFTP with sudo access?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Rezen
  • 435
  • 1
  • 8
  • 23

1 Answers1

0

First, automating su or sudo is not the correct solution.

The correct solution is to setup a dedicated private key with only privileges needed for your task.


The invoke_subsystem and exec_command are generally mutually exclusive. You can use one or the other, but not both. A "subsystem" is kind of an alias to a "command". I.e. the "sftp" subsystem is typically an alias to the "/bin/sftp-server" command (thought that's a very simplified explanation).


There's no native support for executing SFTP subsystem as a different user.

So all you can do is to execute the sftp_server binary directly as a different user.

chan.exec_command('sudo su -c /bin/sftp-server')

(Assuming *nix OpenSSH server)

And you definitely cannot request PTY (get_pty) as that's incompatible with the SFTP protocol.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • I tried this out but it didn't work. If your OpenSSH sshd_config has "Subsystem sftp ", then running this operation does not have any effect on the underlying user. – Parth Shah Apr 25 '18 at 19:39
  • My answer has nothing to do with `Subsystem` directive. It actually bypasses it. So I do not understand your comment. – Martin Prikryl Apr 26 '18 at 05:41
  • I tried out your proposed solution, but kept getting permission denied errors. When I do grep -e "sftp" on my machine, I see that sftp_server is not running. From what I understand, OpenSSH starts the sftp_server process when a sftp connection is being made. In this situation, the solution you have proposed here does not work. – Parth Shah Apr 26 '18 at 05:51
  • What do you mean by "my machine"? Server of client? What *"permission denied errors"*? What do you mean by *"this situation"*? I think you should start a new question as this will hardly get resolved with little information you can provide in comments. – Martin Prikryl Apr 26 '18 at 05:55
  • My question is very similar to this question but I added additional content: https://stackoverflow.com/questions/50035927/running-an-operation-as-a-different-user-via-python-paramiko-sftp – Parth Shah Apr 26 '18 at 06:12