I am trying to connect to a Solaris/Unix
server using a C#
class to read system information/configuration, memory usage etc.
My requirement is to run the commands on the server from a C# application (as we do with a PuTTY
client) and store the response in a string
variable for later processing.
After some research, I found out that SharpSSH
library can be used to do the same.
When I try to run my code, the following line gives me an Auth Fail
exception.
I am confident that the credentials (server name, user name and password) are correct since I am able to log-in from the PuTTY
client with the same credentials.
SshStream ssh = new SshStream(servername, username, password);
What am I doing wrong?
The following is the stack trace if it helps!
at Tamir.SharpSsh.jsch.Session.connect(Int32 connectTimeout)
at Tamir.SharpSsh.jsch.Session.connect()
at Tamir.SharpSsh.SshStream..ctor(String host, String username, String password)
After some research, I found a VB code which pointed me to the right direction. It seems that adding an additional event handler for the KeyboardInteractiveAuthenticationMethod
helped to solve this. Hope this helps someone else.
void HandleKeyEvent(Object sender, AuthenticationPromptEventArgs e)
{
foreach (AuthenticationPrompt prompt in e.Prompts)
{
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
{
prompt.Response = password;
}
}
}
private bool connectToServer()
{
try
{
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(username);
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(username, password);
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(HandleKeyEvent);
ConnectionInfo connectionInfo = new ConnectionInfo(serverName, port, username, pauth, kauth);
sshClient = new SshClient(connectionInfo);
sshClient.Connect();
return true;
}
catch (Exception ex)
{
if (null != sshClient && sshClient.IsConnected)
{
sshClient.Disconnect();
}
throw ex;
}
}