+3 votes
by (240 points)
edited

SftpItem objects provide the owner and group name and IDs, but I do not see a way to check if this applies to the current user except by remembering what name I supplied to Login(). Is it possible using Rebex's SFTP component to retrieve the current user's name, id, and a list of groups the user belongs to?

Applies to: Rebex SFTP

1 Answer

+2 votes
by (148k points)
edited
 
Best answer

SFTP protocol itself doesn't make it possible to retrieve this information from the server, but it runs over SSH. If the logged-in user has permission to execute shell commands over SSH and if the server uses a Unix-like OS, you can use SSH's remote exec capability to determine the information needed.

First, you need the following method (C#):

public static string ExecuteCommand(Sftp sftp, string command)
{
    SshSession ssh = sftp.Session;
    SshChannel channel = null;
    try
    {
        channel = ssh.OpenSession();
        channel.RequestExec(command);

        StringBuilder response = new StringBuilder();
        byte[] buffer = new byte[1024];

        while (channel.State == SshChannelState.Connected)
        {
            if (!channel.Poll(sftp.Timeout*1000, SocketSelectMode.SelectRead))
                break;

            int n = channel.Receive(buffer, 0, buffer.Length);
            response.Append(Encoding.Default.GetString(buffer, 0, n));
        }

        return response.ToString().TrimEnd();
    }
    finally
    {
        if (channel != null)
            channel.Close();
    }
}

You can then use this method with an instance of Sftp object to execute simple commands over the underlying SSH session. Unix commands like whoami, groups or id can be used then:

Sftp sftp = new Sftp();
sftp.Connect(...);
sftp.Login(...);

string userName = ExecuteCommand(sftp, "whoami"); // same as "id -un"
string groupsNames = ExecuteCommand(sftp, "groups"); // same as "id -Gn"

string userId = ExecuteCommand(sftp, "id -u");
string groupId = ExecuteCommand(sftp, "id -g");
string groupsIds = ExecuteCommand(sftp, "id -G");

If you prefer VB.NET, please let me know.

by (240 points)
This worked perfectly (though I implemented it as an extension method instead), thanks!
...