1

I need to copy a file from local to remote /usr/local/bin. I am already using paramiko for some other copy actions.

I saw some solutions online on how to avoid the permission error:

All these solutions:

  • changing who owns the directory
  • adding a user to the group of the directory
  • creating a new group and changing the group on the directory
  • changing the owner
  • Changing the r/w permissions of owner,group, or public.

Don't feel right when working with /user/local/bin.

I also have the option to just copy the file to ~/file to later on move it using an ansible script (which is executed on the remote anyway), but splitting the copying process feels wrong, too.

Directly logging into sudo would be possible since I can enable remote root login, but that sounds like a security issue.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Natan
  • 728
  • 1
  • 7
  • 23

2 Answers2

1

You need to login with the root to have access to folders that require the root access.

For a general discussion on this topic (and why direct root login is not such security problem as commonly believed), see
Allowing automatic command execution as root on Linux using SSH


If your server does not allow direct root login (and you did try to make it happen), you have to find some workaround. Paramiko won't (cannot) help you anyhow with bypassing server's security mechanisms.

Some options:

  • Upload the files to a folder you have a wrote access too, and then automate shell commands (via sudo/su) to copy the files to the final root-only destination.
  • Run Paramiko SFTP via sudo/su. You would have to implement an alternative to SFTPClient.from_transport that will call something like chan.exec_command('sudo su -c /bin/sftp-server') instead of chan.invoke_subsystem("sftp").
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • Your answer solves the question given above. However, for my project I decided to first copy the files to the home directory and then later to `/usr/local/bin` using Ansible. This feels more natural to me than changing paramiko's behavior. – Natan Nov 04 '22 at 12:29
0

In a nutshell:

- name: Copy my file to root owned directory
  ansible.builtin.copy:
    src: /path/to/local-file
    dest: /usr/local/bin
    owner: root
    group: root
    mode: 0750
  become: true

Or if the file is already on your remote

- name: Copy my file to root owned directory
  ansible.builtin.copy:
    remote_src: true
    src: /path/to/remote-file
    dest: /usr/local/bin
    owner: root
    group: root
    mode: 0750
  become: true

Note: the user used to connect to your remote target must have full sudo rights. See Ansible privilege escalation

Zeitounator
  • 38,476
  • 7
  • 53
  • 66
  • I edited my question and clarified that `ansible` is only running remotely not locally. So copying using `ansible` locally while possible feels a bit odd. But I will definitely consider it. – Natan Oct 27 '22 at 06:36