2

I am using C# and Renci.SshNet to open an SFTP connection. I can get the attributes of files just fine, including the owner and group of the file. They are integers however, and figuring out what the user can do requires knowing their user id and group id. This is being done from a Windows machine, so that information is not readily available. How do I get the user id and group id without having the user manually run id -u and id -g on a *nix machine?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Brent
  • 4,153
  • 4
  • 30
  • 63

1 Answers1

2

The Renci SSH.NET library uses the SFTP protocol version 3. In this version of the protocol only the GID and UID numbers are provided as distinct values.

The username and group name are provided in the SFTP protocol version 4 and newer only. But even if SSH.NET did support this version of the protocol, it would not really help, as most SFTP servers (OpenSSH in particular) support the version 3 only anyway.


There's the longname field provided in the listing in the SFTP version 3, where OpenSSH server provides a *nix ls-like record for the file. So it does contain the username and group name. Just the format of the record is platform specific. The SSH.NET simply ignores the field and does not try to parse it (it's not to be parsed actually). See a comment "This field value has meaningless information" in the SftpNameResponse.LoadData():

protected override void LoadData()
{
    ...
    for (int i = 0; i < this.Count; i++)
    {
        var fileName = this.ReadString(this.Encoding);
        this.ReadString();   //  This field value has meaningless information
        ...
    }
}

If you really need the value, you may consider switching to WinSCP .NET assembly, which uses the longname field and exposes the username and group name in the .Owner and .Group properties of the RemoteFileInfo class.

Use the Session.ListDirectory to retrieve the listing.

RemoteDirectoryInfo directory = session.ListDirectory("/home/martin/public_html");

foreach (RemoteFileInfo fileInfo in directory.Files)
{
    Console.WriteLine("{0} owned by {1}:{2}",
        fileInfo.Name, fileInfo.Owner, fileInfo.Group);
}

WinSCP supports also the SFTP versions 4–6, in case your server does support them.

(I'm the author of WinSCP)

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