Skip to content
Advertisement

Python paramiko executing sudo

I am using paramiko put method to send file from local to remote server. However, I am having problem executing sudo su - user command to view the file from remote. I also tried changing the permission from local but the file permission stays intact when transferred.

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(<Host>, username=<User Name>, password=<Password)

sftp = ssh.open_sftp()
sftp.put(<Source>, <Destination>)
sftp.close()

Is there a way to execute sudo su - user command using paramkio so the transferred files can be read from remote?

Thank you!

Advertisement

Answer

no you cannot do this… however you can sort of work around it, by using sudo to move the file after its uploaded

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(<Host>, username=<User Name>, password=<Password)

sftp = ssh.open_sftp()
sftp.put(<Source>, destination_i_CAN_write_to)
sftp.close()

#now move the file to the sudo required area!
stdin, stdout, stderr = ssh.exec_command("sudo -S -p '' mv /uploaded/path/to/file.txt /restricted/sudo/path/file.txt",**kwargs)
stdin.write(SUDO_PASSWORD + "n")
stdin.flush()

the -S flag on sudu tells it to expect the password to come from stdin

the -p '' flag tells sudo to use '' or the empty string as the prompt for the password

you cannot simply use sudo su - username in an exec_command before the call to open_ssh, because each call to exec_command runs in its own subshell, as such the changes will not propagate back to the main session

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement