1

How do I use Paramiko and sudo to run chmod 775?

Code snippet:

    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())    
    r_pass = getpass.getpass(prompt='Remote password? ')   
    ssh_client.connect(r_ip, username=r_name, password=r_pass)
    ftp = ssh_client.open_sftp()
    for fn in files:
        print("sending {} of {}".format(count, len(files)))
        ftp.put(fn, posixpath.join(r_path_mark, fn))
        ftp.chmod(r_path_mark+fn, 0o775)   

The very last ftp.chmod command results in a "permission denied".

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
hal007
  • 11
  • 3
  • 1
    Does this answer your question? [Running Sudo Command with paramiko](https://stackoverflow.com/questions/22587855/running-sudo-command-with-paramiko) – hoodakaushal Feb 11 '20 at 03:19
  • My guess is that sudo is asking for a password via stdin. If the user your connecting as allows password-less sudo I'd think it'd work. Otherwise, I'm not familiar enough with Paramiko to know if it'd let you send a password on stdin to `sudo` *after* being prompted for it. – Oliver Dain Feb 11 '20 at 03:30
  • I'd suggest trying Ansible instead – OneCricketeer Feb 11 '20 at 05:02

3 Answers3

0

There's no standard way to run SFTP over sudo – While not impossible, it involves number of hacks.

For some background my article on using su/sudo with WinSCP SFTP client:
How do I change user after login (e.g. su root)?.


Alternatively, you can run chmod shell command over sudo, what is covered in other questions already:


Though in general, you should not use sudo this way for a command automation.
For alternatives, see:
Allowing automatic command execution as root on Linux using SSH

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
0

Thanks everyone who replied. I did review everyone's feedback. All are good but for our solution, it didnt do it. Thanks also to @cricket_007. My TL suggested I use Ansible as well.

I did get it work. The trick was to call another script wherein the called script resides locally in the remote machine and therefore sudo stuff isn't an issue.

Flow is as follows:

  • App server (script 'A' is invoked by user)
  • App server (script A does its routine and then using subprocess.call it calls script 'B' also residing in the same App server)
  • App server (script 'B' has some magical open source code that I didnt write.. but it invokes a script 'C' residing in a remote server)
  • Remote server (script 'C' is able to run everything as sudo su - locally. No special coding needed as its local to the machine << and that was my original problem to begin with)

All good << Just tested the end to end deployment this morning.

hal007
  • 11
  • 3
0

Execute command directly in your for loop -

stdin, stdout, stderr = ssh.exec_command("sudo su - -c 'chomd 775 $filename'")
JKC
  • 47
  • 8