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?

asked 27 May '10, 18:32

Bill%20W's gravatar image

Bill W
502
accept rate: 0%


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.

link

answered 28 May '10, 14:03

Lukas%20Pokorny's gravatar image

Lukas Pokorny ♦♦
2.2k18
accept rate: 32%

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

(28 May '10, 14:49) Bill W
Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×115
×1

Asked: 27 May '10, 18:32

Seen: 483 times

Last updated: 28 May '10, 14:03