How do I get string username/groupname from numeric uid/gid on remote host in an SFTP session?

Solution 1:

It's not possible.

At least not with the widely used SFTP version 3.

Solution 2:

An easy workaround would be to open an additional SSH session and use regular shell's chown and chgrp commands. But the company I work in uses timed tokens for authentication and, in short, an additional session means additional 30 seconds per host, a non-starter for batch installations.

With -o ControlMaster= and -o ControlPath= you can share multiple sessions over a single network connection (see man 5 ssh_config). Short options for ssh are -M and -S respectively (see man 1 ssh). This approach requires you to authenticate once. sftp from OpenSSH supports -o and can share a connection with ssh.

The procedure:

  1. ssh -Nf -o ControlMaster=yes -o ControlPath=… user@server. The master connection. Here you authenticate before the connection goes to the background.

  2. ssh -o ControlPath=… … and/or sftp -o ControlPath=… … and/or even sshfs (see below). As long as you stick to the chosen control socket (ControlPath) and the master connection works, these commands will use it. Have fun.

    E.g. you can run uid="$(ssh … "id -u someuser")" and use $uid later in your script.

  3. Finally ssh -o ControlPath=… -O exit … to terminate the master connection.

My other answers that may be useful:

  • Answer with a script that creates a temporary directory for the control socket safely.
  • How to use sshfs with shared control socket. The answer includes an interesting note about placeholders.
  • About sshfs in general.