Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 931
Young Avatar asked Mar 09 '23 01:03

Young


1 Answers

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

like image 98
Joran Beasley Avatar answered Mar 27 '23 05:03

Joran Beasley