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

New Post: Is there a way to find the status of a file uploading or completed.

$
0
0
while using sftpclient i noticed that the large files are moved from one folder to another even when they are in uploading status. Is there any attribute to find the status of the file in sftpclient.

New Post: RDP access over a SSH tunnel

$
0
0
We have a bunch of windows servers at various locations. The servers are behind firewalls that don't allow any incoming ports. As a result we cannot Remote Desktop directly to any of the servers from the Internet (without resorting to VPN which is what we do today).

I would like to see if it's possible to create an RDP "broker" service that uses SSH tunneling to facilicate this direct connection. This is what I am thinking based on my understanding of the technology but I am not sure:
  • Set up a windows service on the remote Windows server.
  • Set up another Windows service - the broker - at our HQ.
  • Open up whatever port necessary at HQ for the windows service at the remote location to connect and establish an SSH tunnel with the broker service at HQ.
  • Provide an API in the broker that provides a user with the IP/Port combination they should use with their RDP client depending on the windows server they want to connect with. The IP/port combination is an available combination on the broker server's local network interface.
  • The HQ user starts their Remote Desktop Client application on their PC and connects to the broker on the IP/port provided. Doing so connects the user to the desired windows server.
Is this possible with ssh.net and if so, can you plese provide or point me to some sample code for both the remote service and the broker?

Thanks.

New Post: Command Not found error 127

$
0
0
When we are executing few command the below code is executing successfully but for few commands such as "server_mount ALL" , it is giving error code 127 and command not found error with message "bash: server_mount: command not found"

If we notice carefully the error message does not have ALL text. its only having server_mount . What could be the issue . is the problem with space before ALL

Please suggest a solution.

below is the code i am using I am using dotnet 3.5 latest dll
var client = new SshClient("12.xx.xx.xx", "rootxx", "xxxxx");
        client.Connect();

           string commandName = txtCommand.Text.ToString();
            SshCommand command = client.CreateCommand(commandName);
            command.CommandTimeout = new TimeSpan(24, 0, 0);
            commandResult = command.Execute();
            string error = command.ExitStatus.ToString();
            MessageBox.Show(error);
            MessageBox.Show(command.Error);

New Post: Command Not found error 127

$
0
0
What is "server_mount"?
I suspect it's an own written script or s.th like that?
Try using the absoulte path, e.g /usr/sbin/server_mount (or wherever the script is located).

Greetz

New Post: Command Not found error 127

$
0
0
The command which we are trying to run is "server_mount ALL". This is a command specific to the server and OS. This is such one of the commands which is having problem . My concern is whether the Space in the command is creating any issue.

New Post: Command Not found error 127

$
0
0
Don't think so.
As the error says: bash cannot find the command server_mount.
It never shows your options:

$ foo foo
bash: foo: command not found
$ bla bla
bash: bla: command not found

Try the absolut path.

Commented Issue: Process terminated due to unhandled exception in Finalize / Destructor [1514]

$
0
0
__My application encountered the following unhandled exception that caused the process to exit:__

Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: Renci.SshNet.Common.SshConnectionException
Stack:
at Renci.SshNet.Session.SendMessage(Renci.SshNet.Messages.Message)
at Renci.SshNet.Channels.Channel.SendMessage(Renci.SshNet.Messages.Connection.ChannelCloseMessage)
at Renci.SshNet.Channels.Channel.Close(Boolean)
at Renci.SshNet.Channels.ChannelSession.Close(Boolean)
at Renci.SshNet.Channels.Channel.Dispose(Boolean)
at Renci.SshNet.Channels.ChannelSession.Dispose(Boolean)
at Renci.SshNet.Sftp.SubsystemSession.Dispose(Boolean)
at Renci.SshNet.Sftp.SftpSession.Dispose(Boolean)
at Renci.SshNet.Sftp.SubsystemSession.Finalize()

__This occurred just over 60 seconds _after_ the Dispose method on SftpClient was called which generated a very similar exception (handled and logged by my code):__

2013-02-16 15:41:32.9693 Error SftpFileTransfer Renci.SshNet.Common.SshConnectionException,Client not connected., at Renci.SshNet.Session.SendMessage(Message message)
at Renci.SshNet.Channels.Channel.SendMessage(ChannelCloseMessage message)
at Renci.SshNet.Channels.Channel.Close(Boolean wait)
at Renci.SshNet.Channels.ChannelSession.Close(Boolean wait)
at Renci.SshNet.Channels.Channel.Dispose(Boolean disposing)
at Renci.SshNet.Channels.ChannelSession.Dispose(Boolean disposing)
at Renci.SshNet.Sftp.SubsystemSession.Dispose(Boolean disposing)
at Renci.SshNet.Sftp.SftpSession.Dispose(Boolean disposing)
at Renci.SshNet.SftpClient.Dispose(Boolean disposing)
at Renci.SshNet.BaseClient.Dispose()
at BusinessObjects.SftpFileTransfer.DownloadFiles()


__It looks like ~SubsystemSession() is causing an attempt to send a message over the channel(!) due to the chaining of calls to the various Dispose() methods.__
Comments: ** Comment from web user: wvandoesburg **

I've tested this issue using the current codebase (revision 32250).

I'm still seeing this problem.

The classification "resolved" does not seem correct.

New Post: Download large files never completes, no error

$
0
0
This never completes on files that are close to 2GB
This succeeded on files close to 500MB. Not sure where the threshold is.
But the memory utilization goes up to 5GB+ and bounces up and down indefinitely
                  using (var ms = new MemoryStream())
                        {

                            sftp.BufferSize = 1024 * 16;
                            sftp.DownloadFile(file.FullName, ms);
                        }

New Post: CreateShell

$
0
0
Hi All,

I need to switch to 'root' through a SSH session so I'm using Oleg's code above to try and run 'sudo su' within the SSH session. I was hoping that creating a shell would allow me to run the command. Alas I keep getting the dreaded 'Error: sudo: sorry, you must have a tty to run sudo'
                var input = new MemoryStream();
                var sw = new StreamWriter(input);
                var output = Console.OpenStandardOutput();
                var shell = client.CreateShell(input, output, output, "xterm", 80, 24, 800, 600, "");
                shell.Stopped += delegate
                {
                    Console.WriteLine("\nDisconnected...");
                };

                shell.Started += delegate
                {
                    sw.AutoFlush = true;

                    //  Start Running Commands
                    var cmd1 = client.RunCommand("sudo su");

                    if (cmd1.Error == null)
                    {
                        Console.WriteLine(cmd1.Result);
                    }
                    else if (cmd1.Error != null)
                    {
                        Console.WriteLine("Error: " + cmd1.Error);
                    }
                    shell.Stop();
                };

//  Start the tty shell
                shell.Start();
I would appreciate some assistance if possible.

I am re-directing the console output to a Text box if that makes a difference???

New Post: A question re: activity & timeout...

$
0
0
Experts,

I am trying to figure out how to capture commands' output from routers, switches & servers that respond with a lot on the command line. Like cat'ing a large text file, or a running-config, etc.

Right now, I try to estimate the timeout duration in seconds, but this isn't a reliable way. What I really need is a way to:
  1. fill a variable with the results of command line entry on the host (not using SshCommand, as it wasn't reliable [the way I was doing it])...
  2. wait for activity on the stream to stop for, say, X seconds.
I have tried .Expect(), but again, it is not reliable when using stream (2 handles, in & out, on the same ssh object).

So think of it like another kind of timeout: One that will assume that any data coming in (except the echo'ing back on the stream of the command entered from the client) is good, and somehow maybe monitor ReadLine() or some such to start counting every time a line is read.

If another line of data is read, restart the timer. If this goes on and the timer reaches a threshold (user set), then the stream somehow signals it is done, and the string variable is then assumed to have all the text returned from the command.

Right now the existing timeout() will cut off the stream returned from the server-even if there is still data being written to it.

How do you all solve this?

TIA!

pat
:)

P.S. Thanks, Oleg for keeping this active. I hope to find a way to contribute.

New Post: Renci.SshNet.Common.SshOperationTimeoutException

New Post: CancelAsync() Always seems to timeout

$
0
0
Hi,

I'm currently trying to implement a Job Manager in C# that executes various tasks on Linux and Windows machines via SSH. The idea is to asynchronously execute the task so that the Job Manager can monitor in case the user aborts the job (The job manager is multi-threaded to allow multiple jobs to execute at once).
If the user does abort the job, this is where the problems come in. I'm using CancelAsync() to try and cancel the running process on the remote machine, but for some reason it will always time out and not abort the remote process. Any advice on what I might be doing wrong / could do differently / investigate further would be much appreciate! Sample code for the manager thread below:
client.Connect();
var cmd = client.CreateCommand("python /my/python/script.py 1 2 3");

var async = cmd.BeginExecute();

while (!async.IsComplete)
{
    Thread.Sleep(2000);
    if (job.State == jobState.Aborted)
    {
        cmd.CancelAsync();
    }
}

cmd.EndExecute(async);
...
client.Disconnect();
Many thanks!
Mike

New Post: Feature request: SCPclient reuse existing ssh session

$
0
0
Hello
I'd like scpclient to be able to connect via existing ssh session - one new constructor method like this
public ScpClient(Session sshSession)
I'm going to implement it myself or maybe you are planning it already

Created Unassigned: SSH and SCP without passwords [1829]

$
0
0
Is there a way to allow doing SSH and SCP without passwords?

I can't figure out how to do it with this latest release of SSH .NET.

Please help.

Thanks and regards,
codefinder

New Post: how to get long messages from cisco router

$
0
0
I'm trying to get log from cisco router but it cuts response.

How to get full text messages from router?
>show log
Syslog logging: enabled (11 messages dropped, 0 messages rate-limited,
                0 flushes, 0 overruns, xml disabled, filtering disabled)
    Console logging: level debugging, 54 messages logged, xml disabled,
                     filtering disabled
    Monitor logging: level debugging, 0 messages logged, xml disabled,
                     filtering disabled
    Buffer logging: level debugging, 54 messages logged, xml disabled,
                    filtering disabled
    Logging Exception size (4096 bytes)
    Count and timestamp logging messages: disabled

No active filter modules.

    Trap logging: level informational, 58 message lines logged
 --More--
UPD:
SOLUTION>
            var cmd = client.CreateCommand("show log ");   
            var asynch = cmd.BeginExecute();

            var reader = new StreamReader(cmd.OutputStream);

            while (!asynch.IsCompleted)
            {
                var result = reader.ReadToEnd();
                if (string.IsNullOrEmpty(result))
                    continue;
                Console.Write(result);
            }
            cmd.EndExecute(asynch);

New Post: Ionic.Zlib.dll and multiple operations

$
0
0
I have one SftpClient on which I sometimes do multiple operations simultaneously. Each of these operations happens at a separate thread (I'm using a Parallel.ForEach loop). I've read around here that SftpClient can handle this, and I have not detected any problem with SftpClient itself. But I'm using Ionic.Zlib.dll for zlib compression and it gives me "strange" exceptions when multiple operations occurs. I suspect that Ionic.Zlib.dll either has a problem with thread safety (I know it's not thread safe) or multiple operations at the same time. The exceptions I'm getting is a ArgumentOutofRange exception deep inside Ionic.Zlib.dll. Does anyone has any thoughts or experience with this? I have not had any troubles when using Ionic.Zlib.dll with single operations on a single thread.

I could create a separate SftpClient for each operation, but the operations consists of Exists() and small file transfers so the overhead of creating a new connection each time would be very big. Doing the operations synchronous takes forever. I've also given thought to creating a pool but I would rather not do that.

New Post: Ionic.Zlib.dll and multiple operations

$
0
0
My solution was to implement a new parameter to the ConnectionInfo constructor which controls the usage of compression. Initial testing is very promising, the connection that need compression got it (only used for port forwarding), but the other ones don't. The exceptions that I got before is gone. Under is what I changed (except for all the changes to derived classes of ConnectionInfo). I hope this can help others that get stuck on this.

I replaced
public ConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params AuthenticationMethod[] authenticationMethods)
with
public ConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, bool useCompression, params AuthenticationMethod[] authenticationMethods)
and replaced
this.CompressionAlgorithms = new Dictionary<string, Type>()
{
    //{"zlib@openssh.com", typeof(ZlibOpenSsh)}, 
    //{"zlib", typeof(Zlib)}, 
    {"none", null}, 
};
with
if (!useCompression)
{
    this.CompressionAlgorithms = new Dictionary<string, Type>()
    {
        {"none", null},
    };
}
else
{
    this.CompressionAlgorithms = new Dictionary<string, Type>()
    {
        {"zlib", typeof (Zlib)}, 
    };
}

New Post: How to execute a program in remote server via SSH?

$
0
0
I need to execute a program in remote server via SSH. This program is in c:\windows\system32\

How can I execute this program passing parameters?

Thank you

New Post: how to get long messages from cisco router

$
0
0
uugan,

If you are seeing "--More--", that might mean that your terminal session in the cisco device is at the terminal's number of lines. You can change this to not page by the command:

"terminal pager 0"

This will turn paging off...

New Post: sftp behind proxy unable to connect

$
0
0
Hi Guys,

this may sound familiar but I am unable to get it to connect:

Exception:
at Renci.SshNet.Session.SocketReadLine(String& response)
at Renci.SshNet.Session.ConnectHttp()
at Renci.SshNet.Session.Connect()
at Renci.SshNet.BaseClient.Connect()
at FTPClient.ArchitasSFTPClient.DownLoadFiles() in c:\SFTPClient.cs:line 134
at FTPClientConsoleApp.Program.Main(String[] args) in c:\FTPClientConsoleApp\Program.cs:line 228
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

and the code is:

var connectionInfoz = new ConnectionInfo(_ftpServer, PORT, _userName,
            ProxyTypes.Http, PROXYHOST, PROXY_PORT, _userName, _password,
            new AuthenticationMethod[] { new PasswordAuthenticationMethod(_userName, _password) })
            {
                Timeout = TimeSpan.FromMinutes(15)
            };

        using (var sftp = new SftpClient(connectionInfoz))
        {
            sftp.BufferSize = 1024;
            sftp.ConnectionInfo.Timeout = TimeSpan.FromMinutes(3);
            sftp.OperationTimeout = TimeSpan.FromMinutes(10);
            try
            {
                sftp.KeepAliveInterval = TimeSpan.FromMinutes(10);
                var connectionInfo = sftp.ConnectionInfo;
                Console.WriteLine(connectionInfo.Timeout);
                sftp.Connect(); // this line throws exception after waiting for 3 minutes

            }

            catch (ProxyException ex)
            {
                Console.WriteLine(ex.Message);
            }
}

I can connect to the site via WinSCP without any problems.
Viewing all 2955 articles
Browse latest View live


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