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.