Quantcast
Channel: SSH.NET Library
Viewing all 2955 articles
Browse latest View live

Created Unassigned: Closing forwarded ports does not work [1867]

$
0
0
Dear all,

I use PuTTy with the following settings for port forwarding which works fine:
putty.exe -ssh user@hostname -L 5555:localhost:5555 -L 5554:localhost:5554 -N -pw password


Now I want to do this from C# and therefore I'd like to use the SSH.NET library. So I use the following to forward the ports:
```
public void ForwardPortLocally(uint portNumber)
{
try
{
var p = new ForwardedPortLocal("localhost", portNumber, "localhost", portNumber);
client.AddForwardedPort(p);
p.Start();
}
catch (Exception ex)
{
throw new Exception(String.Format("ERROR: Port forwarding failed: {0}", ex.Message));
}
}
```
I know I need to clean up after my self an therefore I use the following code:
```
public void Dispose()
{
var toDispose = new List<ForwardedPortLocal>();
foreach (var forwardedPort in client.ForwardedPorts.Where(forwardedPort => forwardedPort.IsStarted))
{
forwardedPort.Stop();
toDispose.Add((ForwardedPortLocal)forwardedPort);
}
foreach (var port in toDispose)
{
client.RemoveForwardedPort(port);
port.Dispose();
}
if (client.IsConnected)
{
client.Disconnect();
}
client.Dispose();
}
```
This is where the problem begins. I am not able to close my ports properly. While setting up the forwarded ports is working fine, the attempt to close it always fails.
Once I have setup the forwarded ports and closed the application I am not able to open them anymore because they are still in use and I get the exception:
> "Only one usage of each socket address (protocol/network address/port) is normally permitted"

I have used sysinternals' tcpview to see whether the ports stay open and they do but the process is "non-existent". I have to logg off and on again from Windows to be able to re-open the port.

Am I doing something wrong? Have I found a bug in the library?

Regards


P.S.: I also experienced that the method i use to get rid of the forwarded ports takes seconds to run which is very long and seems a bit odd to me.

New Post: SSH Tunnel / Port Forwarding

$
0
0
In my opinion you are using a wrong connection string.
After forwarding your local port to the remote one through ssh, you must connect using "locahost", not "data".
More, MySql standard port is 3306, not 3307, so you should declare it in connection string.
So you should use
string connStr = "server=localhost;port=3307;database=db_name;uid=my_sql_username;pwd=my_sql_server_password;"; 
Hope this solves your problem,
Marco

New Post: Need latest DLL for .net 3.5 framework

$
0
0

Why not just compile? Thankfully, the classes were put together correctly.

I modified the source as posted previously, made a new c# project in my solution, and it compiled to dll first time under 4.5.

Does this fail for you?

New Post: Unable to connect to : Exception calling "Connect" with "0" argument(s): "No suitable authentication method found to complete authentication."

Created Unassigned: Connection through proxy [1869]

$
0
0
Hi,

I have an issue through a Symantec Web Gateway proxy server HTTP . The connection is made through to the proxy server but the authentication isn't passed and the connection fails. Is there something I can do to allow this, like a setting. Or is this just an inherent issue with the Proxy? Has anyone else had this experience?


Thanks

New Post: SFTP Middleman Transfer

$
0
0
Is there a way to have my application act as a "middleman" without saving the file locally? For example, a user clicks a button than the application grabs a file from SFTP Server A, then transfers it to SFTP Server B without me having to save the file locally in between.

Created Unassigned: Unable to connect to : Exception calling "Connect" with "0" argument(s): "No suitable authentication method found to complete authentication." [1871]

$
0
0
Hello,

After doing Import-Module SSH-Sessions, I try to connect as follows:

PS C:> New-SshSession -ComputerName 10.220.12.220 -Username username -Password ***********
Unable to connect to 10.220.12.220: Exception calling "Connect" with "0" argument(s): "No suitable authentication method found to complete authentication."

I can to it connect using putty. The putty log shows me this (hoe this helps):

2014-01-16 06:53:21 Looking up host "10.220.12.220"
2014-01-16 06:53:21 Connecting to 10.220.12.220 port 22
2014-01-16 06:53:21 Server version: SSH-2.0-OpenSSH_4.2
2014-01-16 06:53:21 Using SSH protocol version 2
2014-01-16 06:53:21 We claim version: SSH-2.0-PuTTY_Snapshot_2010_05_02:r8934
2014-01-16 06:53:21 Doing Diffie-Hellman group exchange
2014-01-16 06:53:21 Doing Diffie-Hellman key exchange with hash SHA-1
2014-01-16 06:53:23 Host key fingerprint is:
2014-01-16 06:53:23 ssh-rsa 2048 <some hex string>
2014-01-16 06:53:23 Initialised AES-256 CBC client->server encryption
2014-01-16 06:53:23 Initialised HMAC-SHA1 client->server MAC algorithm
2014-01-16 06:53:23 Initialised AES-256 CBC server->client encryption
2014-01-16 06:53:23 Initialised HMAC-SHA1 server->client MAC algorithm
2014-01-16 06:53:40 Access granted
2014-01-16 06:53:40 Opened channel for session
2014-01-16 06:53:40 Allocated pty (ospeed 38400bps, ispeed 38400bps)
2014-01-16 06:53:40 Started a shell/command

New Post: An established connection was aborted by the software in your host machine - ForwardedPortLocal

$
0
0
Hi!

At the moment I am a bit unsure if it is due to using the ForwardedPortLocal and that my requests to the server side not always turns out to be ok, or how I should but it.

Have created a camera surveillance software that utilise the Renci SshNet library for creating a port forwarding to a connected camera on the server side.

It seems as long as I only let the remote side to send data to client side it seems to work out ok. No error throws back, but If I try to send commands to the device on the server side it tends to maybe work the first time very well and the second time, an suddenly it throws this error, and when I log the error on the client side I get this stacktrace:
at Renci.SshNet.Session.SocketRead(Int32 length, Byte[]& buffer)
   at Renci.SshNet.Session.Read(Int32 length)
   at Renci.SshNet.Session.ReceiveMessage()
   at Renci.SshNet.Session.MessageListener()
The client side sends different commands (over http) to the connect device (connected with WIFI to the server)), and the client side reads from the server side on http (an MJPEG-stream).

Section for creating the forwarded port (at the moment only one device is used.)
        private static Random _rnd = new Random(); 
        private void ProcessCameras()
        {
            int addrnr = 1;

            foreach (IPCamera camera in _cameras)
            {
                string addr = string.Format("127.0.0.{0}", addrnr);

                // int rndport = _rnd.Next(49152, 65535); // IANA suggests the range 49152 to 65535 for dynamic or private ports.
                // IPEndPoint ep = new IPEndPoint(IPAddress.Parse(addr), rndport); 

                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(addr), 3333); 
                
                ForwardedPortLocal port = new ForwardedPortLocal(ep.Address.ToString(), (uint)ep.Port, camera.RemoteLocalEndpoint.Address.ToString(),(uint)camera.RemoteLocalEndpoint.Port);
                addrnr += 1;

                _client.AddForwardedPort(port);

                port.Start();
                port.Exception += PortException;
                port.RequestReceived += port_RequestReceived;

                camera.LocalEndPoint = ep;
                camera.Index = _cameras.IndexOf(camera);
                camera.StartReceive();
            }

        }
And here is how I initiate the sshclient
 public void Connect()
        {

            try
            {

                if (_client == null)
                {

                    if (_connectiontype == ConnectionType.Password)
                    {
                        _client = new SshClient(_host, _port, _user, _password);
                    }

                    if (_connectiontype == ConnectionType.PrivateKey)
                    {
                        _client = new SshClient(_host, _port, _user, _privatekey);
                    }

                    _client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 15); 
                    _client.KeepAliveInterval = new TimeSpan(0,0,10); 
                    _client.ErrorOccurred += SshClientErrorOccurred;
                    _client.Connect();

                    var e = new StateChangedEventArgs();

                    if (_client.IsConnected)
                    {
                        e.Connected = true;
                        StateChanged(this, e);
                        ProcessCameras();
                    }
                    else
                    {
                        e.Connected = false;
                        StateChanged(this, e);
                    }

                }
            }
            catch (Exception ex)
            {
                ErrorRaised(this, new ErrorEventArgs(ex)); 
            }
I have not been able to log on the server side yet to see whats happend. But Im a bit confused why it always only dies when sending commands, not when Im only reading the MJPEG-stream. My own programlog gives me following:
2014-01-20 10:50:52 Starting application

2014-01-20 10:51:03 StartReceive fired off!

2014-01-20 10:51:03 port_RequestReceived: '127.0.0.1:7283'

2014-01-20 10:51:03 port_RequestReceived: '127.0.0.1:7284'

2014-01-20 10:51:06 Sending pan/tilt command.

2014-01-20 10:51:06 port_RequestReceived: '127.0.0.1:7291'

2014-01-20 10:51:07 port_RequestReceived: '127.0.0.1:7292'

2014-01-20 10:51:07 En befintlig anslutning tvingades att stänga av fjärrvärddatorn StackTrace:    at Renci.SshNet.Session.WaitHandle(WaitHandle waitHandle)
   at Renci.SshNet.Channels.Channel.WaitHandle(WaitHandle waitHandle)
   at Renci.SshNet.Channels.ChannelDirectTcpip.Open(String remoteHost, UInt32 port, Socket socket)
   at Renci.SshNet.ForwardedPortLocal.<>c__DisplayClass3.<InternalStart>b__2()

2014-01-20 10:51:07 port_RequestReceived: '127.0.0.1:7293'

2014-01-20 10:51:07 Session is not connected. StackTrace:    at Renci.SshNet.Channels.ChannelDirectTcpip.Open(String remoteHost, UInt32 port, Socket socket)
   at Renci.SshNet.ForwardedPortLocal.<>c__DisplayClass3.<InternalStart>b__2()

2014-01-20 10:51:07 The underlying connection was closed: An unexpected error occurred on a receive. StackTrace:    at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at IpCamera.Library.Cameras.MjpegIPCamera.RespCallback(IAsyncResult ar) in c:\Projekt\TFS\IpCamera\IpCamera.Library\Cameras\MjpegIPCamera.cs:line 156

Any hunch? Any ideas? Any?

New Post: SftpClient.Exists always return true

$
0
0
I've just bumped into this issue as well. It only seems to occur when using a remote sshd for me.

The issue tracker appears to be down. Was there a useful workaround in the bug report?

New Post: Tailing a file as its being written

$
0
0
Any update on the problem with the complete reprint of the output?

Created Unassigned: lsnrctl: command not found issue [1874]

$
0
0
Hi,

I am facing issue while trying to run a command on a remote server using renci.dll
The error is as below

bash: lsnrctl: command not found

and command used as -

lsnrctl status | egrep -i 'security'

Whereas same if I run the same command through ssh (i.e remotely connecting through putty) , I am able to get the command output.

thanks

New Post: Tailing a file as its being written

$
0
0
So here's how I did it, it works-ish, but sometimes randomly disconnects or stops tailing. Let me know if you have any questions.
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(LogData.IpAddress, LogData.Username, LogData.Password);

using (var ssh = new SshClient(connectionInfo))
{
    ssh.Connect();
    string reply = String.Empty;

    using (var shellStream = ssh.CreateShellStream("dumb", 0, 0, 0, 0, BUFFERSIZE)) // BUFFERSIZE Set to 1024 for me
    {
        // Wait for prompt
        reply = shellStream.Expect(new Regex(LogData.ServerName.ToLower() + @":.*>"), new TimeSpan(0, 0, 10));
        shellStream.WriteLine(command);  // command is the tail command, ie "tail -f filename"
    
        // Keep reading until a cancel request is given
        while (!WorkerThread.CancellationPending)
        {
            string result = shellStream.ReadLine(new TimeSpan(0, 0, 10));
    
            if (!String.IsNullOrEmpty(result) && !result.Contains(LogData.ServerName.ToLower()))
                UpdateTailActiveTextBox(result);
        }
    }
}

New Post: Use SSH.NET for regular FTP

$
0
0
Hi,
this may sound like a stupid question, but can I use SSH.NET for regular FTP connections and downloads?
I'd like to use this since I'm already familiar with their syntax for SftpClient.
Regards, Stefan

New Post: SSH Tunnel / Port Forwarding

$
0
0
I had the problem when I used that override:
public ForwardedPortLocal(uint boundPort, string host, uint port);
var port = new ForwardedPortLocal(27017, "127.0.0.1", 27017);
Instead, I used
var port = new ForwardedPortLocal("127.0.0.1", 27017, "127.0.0.1", 27017);
and forwarding started working.

New Post: An established connection was aborted by the software in your host machine - ForwardedPortLocal

$
0
0
Could this be an reason to why the ssh-server drops the connection, an SSH_MSG_CHANNEL_CLOSE to an already closed channel?

bump

New Post: An established connection was aborted by the software in your host machine - ForwardedPortLocal

$
0
0
Have identified the cause to why dropbear_0.52 disconnects my application now and then. After some work I was able to get a log from the remote device and could see that SSH.NET sends an EOF with wrong channelnumber, (unknown channel 1) which makes dropbear to exit after auth.
authpriv.info dropbear [3586] exit after auth (admin): EOF for unknown channel 1

Created Unassigned: Sending EOF on wrong channel number. [1877]

$
0
0
In the latest version under Source Code I always gets problem with my devices that runs dropbear_0.52 after a few/seconds 10-20 seconds.

I took a look in the log on one the devices and could see that it exited because of wrong channelnumber on the EOF. Took a look in the source code and could see in the ChannelDirectTcpip.cs that it tries to send an ChannelEofMessage before calling the base.Close() of Channel.

According to the (http://www.ietf.org/rfc/rfc4254.txt , Page 8) it states that:
A party MAY send SSH_MSG_CHANNEL_CLOSE without having sent or received SSH_MSG_CHANNEL_EOF.

Made following change in the ChannelDirectTcpip class.

```
public override void Close()
{
// Close socket if still open
if (this._socket != null)
{
this._socket.Dispose();
this._socket = null;
}

// Send EOF message first when channel need to be closed
// this.SendMessage(new ChannelEofMessage(this.RemoteChannelNumber));

base.Close();
}
```
It seems to let my application to proceed with out getting disconnect by the host after a few seconds when doing requests through the localportforwarding.

New Post: ssh.net $Path not returning everything

$
0
0
the most secure/sure way, is to edit your sshd_config file, add "PermitUserEnvironment yes", restart sshd, then create a file ~/.ssh/environment and set the environment variable you want.
where can I find the config file?
I would prefer not to do
"pwd; echo $PATH" => "pwd; PATH=$PATH:/something echo $PATH"
as there're lots of env variables.

New Post: ssh to debian, then telnet to other devices

$
0
0
hi im elhave and im newbie in coding

need help. i have same issue
  1. i want to connect to ssh server first.
  2. from that ssh server i want to telnet to other server/cisco router
i have succesfully got into ssh server.
but the telnet command, and any other command that return as question from the ssh server or ask back an input from me just don't work.

here's how i write the code



class Program
{
    static void Main(string[] args)
    {
        string userName = "elhave";
        string serverName = "192.168.1.1";//mysshserver
        string password = "mypass";


        var keyboardAuthMethod = new KeyboardInteractiveAuthenticationMethod(userName);
        keyboardAuthMethod.AuthenticationPrompt += delegate(Object senderObject, AuthenticationPromptEventArgs eventArgs) {
            foreach (var prompt in eventArgs.Prompts){
                        if (prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase)) {
                            prompt.Response = password;
                        }                 
            }             
        };             

        var passwordAuthMethod = new PasswordAuthenticationMethod(userName, password);
        var connectInfo = new ConnectionInfo(serverName, userName, passwordAuthMethod, keyboardAuthMethod);

        string hasil = "";
        using (var serverConnection = new SshClient(connectInfo))
        {
            serverConnection.Connect(); 
            var command = serverConnection.RunCommand("who");//inisialization
            while (true)
            {
                command.Dispose();
                nextcommand = Console.ReadLine();
                command = serverConnection.RunCommand(nextcommand);
                Console.Write(command.Result);
                if (nextcommand == "break") {

                    break;
                }
            }



        }
    }
}
}


i expect the app to work like putty. read command, run command, and display the result. but seems like i cant perform it with this code.
here i type man command that will return question from server.
on putty it worked but on my application it did work.
Image

Created Unassigned: Executing Powershell command through freeSSHd & WinSSHD is blocking SSH.NET [1879]

$
0
0
The SSH.NET library is locking up when I run a Powershell script through freeSSHd and WinSSHD. Executing VBScripts through cscript.exe works without issue. I have included example C# code for both (see below). In both cases, the scripts simply involves writing a string to STDOUT.

Stepping into the code, the code is blocking on Session.SocketRead after the SSH_MSG_CHANNEL_DATA message occurs. More specifically, executing the VBScript command generates a SSH_MSG_CHANNEL_REQUEST message, but executing the Powershell command does not.

I have tested the command line in a Command Prompt as well as executing it through an SSH client (putty) without issue. Can anyone give me a workaround or confirm whether this is a bug in the SSH.NET or freeSSHd?

// This works without issue
var client = new Renci.SshNet.SshClient("127.0.0.1", "username", "password");
client.Connect();
var command = client.CreateCommand("cscript.exe /nologo C:\test.vbs");
command.Execute();

// This blocks
var client = new Renci.SshNet.SshClient("127.0.0.1", "username", "password");
client.Connect();
var command = client.CreateCommand("PowerShell.exe C:\test.ps1");
command.Execute();

'VBScript script
WScript.Echo "This is my output"

#Powershell script
Write-Host "This is my output"
Viewing all 2955 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>