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

New Post: Does SSH Class need shell access on remote Linux system ?

$
0
0
When i use SSH.RunCommand and send Unix commands... is it necessary for the user used by the SSH to have a shell access or not ?
Today i configured the SSH and the user had /bin/scponly and the command i sent using the SSH was executed with no exception ...
The SSH component needs also Shell access or not ?

New Post: How to deal with the error stream when using ShellStream

$
0
0
            client.Connect();

            var shell = client.CreateShellStream("test", 80, 24, 800, 600, 1024);
            var input = "cd /nonexistant";
            shell.DataReceived += (sender, args) => Console.Write(client.ConnectionInfo.Encoding.GetString(args.Data));
            shell.Expect(new Regex(@"\$ $")); // CMD prompt
            shell.WriteLine(input);            
=>
Welcome to Ubuntu 14.04.1 LTS (GNU/Linux 3.13.0-44-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

  System information as of Mon Feb  2 13:07:03 CET 2015

Last login: Mon Feb  2 13:07:03 2015 from xxx.xxx.xxx.xxx
~$ cd /nonexistant
-bash: cd: /nonexistant: No such file or directory
~$
Maybe your Regex is wrong or your Thread.Sleep(200) (which is basically just guessing by you)?

Why don't you use RunCommand instead of guessing and trying to find the command prompt:
            var cmd = client.RunCommand("cd /nonexistant");
            Console.WriteLine("STDERR: " + cmd.Error);
            Console.WriteLine("ERRORCODE: " + cmd.ExitStatus);
            Console.WriteLine("STDOUT: " + cmd.Result);

New Post: How to deal with the error stream when using ShellStream

$
0
0
thanks, i will try your codes .
the reason why not using RunCommand it that when i test running "nohup" command or a script containing "nohup" command and the command is finished,the program is disappeared.so i need a shell.
about "Thread.Sleep(200)".when i remove the stop,the output sometimes runs wrong. so i try to find some examples in the discussion area, and then i find some codes like this.

New Post: How to deal with the error stream when using ShellStream

$
0
0
Yeah... Don't use Thread.Sleep() here. This is just guessing and makes your code unreliable.
Example: Replace your "ping -c 10 127.0.0.1" with a "ping -c 10 google.com" and it will fail. Since it takes more than 200 ms for a ping reply.

New Post: How to deal with the error stream when using ShellStream

$
0
0
On second glance i found a bug in your code:
                if (shells.CanRead)
                    output = shells.ReadLine();
                match = regex.Match(output);
match.Success will never become true. ReadLine() blocks till a newline appears.
But the shell-prompt "user@host:~$" doesn't have one
=> endless blocking of Readline() and your loop would never exit.

Created Unassigned: Permission Denied while doing an SFTP with Public Private Key combination [2615]

$
0
0
Hi,

We have an intermittent issue where the SFTP fails when we use the Public Private key mode of authentication.

Below is the code snippet which is used to connect to SFTP.

using(Renci.SshNet.SftpClient sftpClient = new Renci.SshNet.SftpClient( AppConfigHelper.Axway_FTPServer,
AppConfigHelper.Axway_FTPUserName,
new Renci.SshNet.PrivateKeyFile[] {
new Renci.SshNet.PrivateKeyFile(File.OpenRead(AppConfigHelper.PrivateKeyFilePath), AppConfigHelper.Passphrase)
}))

{
try
{
sftpClient.Connect();
sftpClient.ChangeDirectory(AppConfigHelper.Axway_UploadFolderName);
using (FileStream fs = new FileStream(fileNameWithPath, FileMode.Open))
{
sftpClient.UploadFile(fs, completeFileName);
LogHelper.LogInfo(string.Format("File {0} uploaded successfully",completeFileName));
}
}
catch (Exception ex)
{
LogHelper.LogInfo(string.Format("File {0} upload failed", completeFileName));
}
finally
{
if (sftpClient != null)
{
if (sftpClient.IsConnected)
sftpClient.Disconnect();

sftpClient.Dispose();
}
}
}


The issue is very intermittent (happens only once in maybe 50 times or 100 times) and doesn't happen at all when we use the password mode of authentication (So we want to know what is wrong with the Public Private key mode of authentication).

For some reason it is not able to connect to the SFTP server and throws the error "Permission Denied".

When I check for sftpClient.IsConnected, sftpClient.ConnectionInfo.IsAuthenticated, both are false when the SFTP fails.

Kindly let us know if there is a suggestion/solution/work around for this problem.

Thanks & Regards,
Sindoor
Sindhoor.bj@gmail.com

Commented Unassigned: Permission Denied while doing an SFTP with Public Private Key combination [2615]

$
0
0
Hi,

We have an intermittent issue where the SFTP fails when we use the Public Private key mode of authentication.

Below is the code snippet which is used to connect to SFTP.

using(Renci.SshNet.SftpClient sftpClient = new Renci.SshNet.SftpClient( AppConfigHelper.Axway_FTPServer,
AppConfigHelper.Axway_FTPUserName,
new Renci.SshNet.PrivateKeyFile[] {
new Renci.SshNet.PrivateKeyFile(File.OpenRead(AppConfigHelper.PrivateKeyFilePath), AppConfigHelper.Passphrase)
}))

{
try
{
sftpClient.Connect();
sftpClient.ChangeDirectory(AppConfigHelper.Axway_UploadFolderName);
using (FileStream fs = new FileStream(fileNameWithPath, FileMode.Open))
{
sftpClient.UploadFile(fs, completeFileName);
LogHelper.LogInfo(string.Format("File {0} uploaded successfully",completeFileName));
}
}
catch (Exception ex)
{
LogHelper.LogInfo(string.Format("File {0} upload failed", completeFileName));
}
finally
{
if (sftpClient != null)
{
if (sftpClient.IsConnected)
sftpClient.Disconnect();

sftpClient.Dispose();
}
}
}


The issue is very intermittent (happens only once in maybe 50 times or 100 times) and doesn't happen at all when we use the password mode of authentication (So we want to know what is wrong with the Public Private key mode of authentication).

For some reason it is not able to connect to the SFTP server and throws the error "Permission Denied".

When I check for sftpClient.IsConnected, sftpClient.ConnectionInfo.IsAuthenticated, both are false when the SFTP fails.

Kindly let us know if there is a suggestion/solution/work around for this problem.

Thanks & Regards,
Sindoor
Sindhoor.bj@gmail.com
Comments: ** Comment from web user: sindhoor_bj **

Please note that we created the public private key combination using the Putty generator tool.

Commented Unassigned: Permission Denied while doing an SFTP with Public Private Key combination [2615]

$
0
0
Hi,

We have an intermittent issue where the SFTP fails when we use the Public Private key mode of authentication.

Below is the code snippet which is used to connect to SFTP.

using(Renci.SshNet.SftpClient sftpClient = new Renci.SshNet.SftpClient( AppConfigHelper.Axway_FTPServer,
AppConfigHelper.Axway_FTPUserName,
new Renci.SshNet.PrivateKeyFile[] {
new Renci.SshNet.PrivateKeyFile(File.OpenRead(AppConfigHelper.PrivateKeyFilePath), AppConfigHelper.Passphrase)
}))

{
try
{
sftpClient.Connect();
sftpClient.ChangeDirectory(AppConfigHelper.Axway_UploadFolderName);
using (FileStream fs = new FileStream(fileNameWithPath, FileMode.Open))
{
sftpClient.UploadFile(fs, completeFileName);
LogHelper.LogInfo(string.Format("File {0} uploaded successfully",completeFileName));
}
}
catch (Exception ex)
{
LogHelper.LogInfo(string.Format("File {0} upload failed", completeFileName));
}
finally
{
if (sftpClient != null)
{
if (sftpClient.IsConnected)
sftpClient.Disconnect();

sftpClient.Dispose();
}
}
}


The issue is very intermittent (happens only once in maybe 50 times or 100 times) and doesn't happen at all when we use the password mode of authentication (So we want to know what is wrong with the Public Private key mode of authentication).

For some reason it is not able to connect to the SFTP server and throws the error "Permission Denied".

When I check for sftpClient.IsConnected, sftpClient.ConnectionInfo.IsAuthenticated, both are false when the SFTP fails.

Kindly let us know if there is a suggestion/solution/work around for this problem.

Thanks & Regards,
Sindoor
Sindhoor.bj@gmail.com
Comments: ** Comment from web user: da_rinkes **

Check the logs of your ssh server.


New Post: Pageant integration?

$
0
0
Sorry to double post but no one has a copy of this patch?

New Post: How to deal with the error stream when using ShellStream

$
0
0
thanks for all reply
i have done the work.
here is my code.
        string input = String.Empty;
        string output = String.Empty;
        bool isFirst = true;
 
       private void SSHConnect()
        {
            client = new SshClient("172.19.118.141", "trade", "trade");
            client.ConnectionInfo.Encoding = ASCIIEncoding.Default;
            client.Connect();
            ShellStream shells = client.CreateShellStream("test", 80, 24, 800, 600, 1024);
            input = "ping 127.0.0.1 -c 5";
            shells.DataReceived += new EventHandler<Renci.SshNet.Common.ShellDataEventArgs>(shells_DataReceived); 
            shells.Expect(new Regex(@"\$ $")); 
            shells.WriteLine(input);
            shells.Expect(new Regex(@"\$ $")); 
            client.Disconnect();
        }

        void shells_DataReceived(object sender, Renci.SshNet.Common.ShellDataEventArgs e)
        {
            string newline = (client.ConnectionInfo.Encoding.GetString(e.Data));
            if (newline.Contains('\n'))
            {
                Regex regex = new Regex(@"\[.*@.*\][\$|\#]");
                string[] str = newline.Split('\n');
                for (int i = 0; i < str.Length; i++)
                {
                    output += str[i];
                    var match = regex.Match(output);
                    if (output.StartsWith("Last login") || match.Success || output == String.Empty)
                    { output = String.Empty; continue; }
                    if (isFirst && output == input)
                    { output = String.Empty; isFirst = false; continue; }
                    Console.WriteLine(output);
                    output = String.Empty;
                }
            }
            else
                output += newline;
        }

New Post: Accept Host Key Automatically?

New Post: Pageant integration?

$
0
0
I believe this is the patch you are looking for. I use this in some sshnet tools. I did have to tweak one file to deal with the security differences in windows 7 (pageantprotocol.cs) so I've attached that as well. I did not attempt to use the sftp portion so I can't say if that works or not.

New Post: Pageant integration?

$
0
0
I guess my attachments didn't post correctly from my mobile. I will get these posted this evening.

New Post: Pageant integration?

$
0
0
Thank you for doing that xl600! I noticed your changes above so was going to do those anyway. If you removed the SFTP portion in your patch if you have the original that would be great as I plan to try and use both.

Thank you again

New Post: ConnectionInfo.Timeout Exception

$
0
0
When a ConnectionInfo.Timeout is defined for a sftp connection or the default 30 seconds is used, what happens when that time has elapsed. Is an exception thrown like SshOperationTimeoutException? I tried finding this information in the documentation, but maybe I'm overlooking it.

Patch Uploaded: #17214

$
0
0

xl600 has uploaded a patch.

Description:
This is a re-upload of a previously declined pageant integration patch by mladjenovic. The original download link mentioned in discussion https://sshnet.codeplex.com/discussions/434618 is no longer valid and a request was made to have this patch made available.

New Post: Pageant integration?

$
0
0
I had to upload the old patch files as a new patchid (Which will most certainly be declined). It is available here. The modification for Windows 7 to pageantprotocol.cs follows:
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Net;
using System.Text;
using Renci.SshNet.Common;
using System.Security.AccessControl;

namespace Renci.SshNet.Pageant
{
   public class PageantProtocol:IAgentProtocol
    {

        #region  Constants

        private const int WM_COPYDATA = 0x004A;

        private const int AGENT_COPYDATA_ID = unchecked((int)0x804e50ba);

        private const int AGENT_MAX_MSGLEN = 8192;

        public const byte SSH2_AGENTC_REQUEST_IDENTITIES = 11;

        public const byte SSH2_AGENT_IDENTITIES_ANSWER = 12;

        public const byte SSH2_AGENTC_SIGN_REQUEST = 13;

        public const byte SSH2_AGENT_SIGN_RESPONSE = 14;

        #endregion


       public static bool IsRunning
       {
           get
           {
               var hWnd = NativeMethods.FindWindow("Pageant", "Pageant");

               return hWnd != IntPtr.Zero;
           }
       }



        public PageantProtocol()
        {
            var hWnd = NativeMethods.FindWindow("Pageant", "Pageant");

            if (hWnd == IntPtr.Zero)
            {
                throw new SshException("Pageant not running");
            }
            
        }


        #region Implementation of IAgentProtocol

        IEnumerable<IdentityReference> IAgentProtocol.GetIdentities()
        {
            var hWnd = NativeMethods.FindWindow("Pageant", "Pageant");

            if (hWnd == IntPtr.Zero)
            {
                yield break;
            }

            string mmFileName = Path.GetRandomFileName();
            
            using (var mmFile = MemoryMappedFile.CreateNew(
                mmFileName,
                AGENT_MAX_MSGLEN))
            {
                var security = mmFile.GetAccessControl();
                security.SetOwner(System.Security.Principal.WindowsIdentity.GetCurrent().User);
                mmFile.SetAccessControl(security);

                using (var accessor = mmFile.CreateViewAccessor())
                {
                    accessor.Write(0, IPAddress.NetworkToHostOrder(AGENT_MAX_MSGLEN - 4));
                    accessor.Write(4, SSH2_AGENTC_REQUEST_IDENTITIES);

                    var copy = new COPYDATASTRUCT(AGENT_COPYDATA_ID, mmFileName);

                    if (NativeMethods.SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, ref copy) == IntPtr.Zero)
                    {
                        accessor.Dispose();
                        mmFile.Dispose();
                        File.Delete(mmFileName);
                        yield break;
                    }

                    if (accessor.ReadByte(4) != SSH2_AGENT_IDENTITIES_ANSWER)
                    {
                        accessor.Dispose();
                        mmFile.Dispose();
                        File.Delete(mmFileName);
                        yield break;
                    }

                    int numberOfIdentities = IPAddress.HostToNetworkOrder(accessor.ReadInt32(5));

                    if (numberOfIdentities == 0)
                    {
                        accessor.Dispose();
                        mmFile.Dispose();
                        File.Delete(mmFileName);
                        yield break;
                    }

                    int position = 9;
                    for (int i = 0; i < numberOfIdentities; i++)
                    {
                        int blobSize = IPAddress.HostToNetworkOrder(accessor.ReadInt32(position));
                        position += 4;

                        var blob = new byte[blobSize];

                        accessor.ReadArray(position, blob, 0, blobSize);
                        position += blobSize;
                        int commnetLenght = IPAddress.HostToNetworkOrder(accessor.ReadInt32(position));
                        position += 4;
                        var commentChars = new byte[commnetLenght];
                        accessor.ReadArray(position, commentChars, 0, commnetLenght);
                        position += commnetLenght;

                        string comment = Encoding.ASCII.GetString(commentChars);
                        string type = Encoding.ASCII.GetString(blob, 4, 7);// needs more testing kind of hack

                        accessor.Dispose();
                        mmFile.Dispose();
                        File.Delete(mmFileName);

                        yield return new IdentityReference(type,blob,comment);

                    }

                    accessor.Dispose();
                    mmFile.Dispose();
                    File.Delete(mmFileName);
                }
            }
        }
        
        byte[] IAgentProtocol.SignData(IdentityReference identity, byte[] data)
        {
            var hWnd = NativeMethods.FindWindow("Pageant", "Pageant");

            if (hWnd == IntPtr.Zero)
            {
                return new byte[0];
            }

            string mmFileName = Path.GetRandomFileName();

            using (var mmFile = MemoryMappedFile.CreateNew(mmFileName,AGENT_MAX_MSGLEN))
            {
                using (var accessor = mmFile.CreateViewAccessor())
                {
                    var security = mmFile.GetAccessControl();
                    security.SetOwner(System.Security.Principal.WindowsIdentity.GetCurrent().User);
                    mmFile.SetAccessControl(security);

                    accessor.Write(0, IPAddress.NetworkToHostOrder(AGENT_MAX_MSGLEN - 4));
                    accessor.Write(4, SSH2_AGENTC_SIGN_REQUEST);
                    accessor.Write(5, IPAddress.NetworkToHostOrder(identity.Blob.Length));
                    accessor.WriteArray(9, identity.Blob, 0, identity.Blob.Length);
                    accessor.Write(9 + identity.Blob.Length, IPAddress.NetworkToHostOrder(data.Length));
                    accessor.WriteArray(13 + identity.Blob.Length, data, 0, data.Length);

                    var copy = new COPYDATASTRUCT(AGENT_COPYDATA_ID, mmFileName);

                    if (NativeMethods.SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, ref copy) == IntPtr.Zero)
                    {
                        accessor.Dispose();
                        mmFile.Dispose();
                        File.Delete(mmFileName);
                        return new byte[0];
                    }

                    if (accessor.ReadByte(4) != SSH2_AGENT_SIGN_RESPONSE)
                    {
                        accessor.Dispose();
                        mmFile.Dispose();
                        File.Delete(mmFileName);
                        return new byte[0];
                    }

                    int size = IPAddress.HostToNetworkOrder(accessor.ReadInt32(5));
                    var ret = new byte[size];
                    accessor.ReadArray(9, ret, 0, size);

                    accessor.Dispose();
                    mmFile.Dispose();
                    File.Delete(mmFileName);

                    return ret;
                }
            }
        }

        #endregion
    }
}

New Post: Illegal characters in SFTP File upload

$
0
0
I see so I think ill need to change the code in UploadFile to remove these breaks?

New Post: Stability while in beta; "stable" timeframe

$
0
0
drieseng wrote:
I've been working on performance tuning lately, but I'll now focus on fixing the following issue:
  • issue 2591: Session.Disconnect() hangs forever
Once that issue is fixed, we'll probably release one more beta.
There should only be a week or two between that beta and the stable release.

Thanks for the patience!
drieseng, It looks like issue 2591 was resolved on Dec 22, 2014 with change set 41297. Can you give us an update on a stable release time frame?

New Post: BeginSynchronizeDirectories Example

$
0
0
Does anyone have an example usage of BeginSynchronizeDirectories? I'm currently using this statement:
IEnumerable<FileInfo> fileInfo = sftpClient.SynchronizeDirectories(sourceDirectory, destinationDirectory, "*");
But obviously in the GUI it freezes up as the directories are being synced because it's not asynchronous.

My main question is, dealing with the state object and the asynchronous call back, so my existing code is:
IAsyncResult asyncResult = sftpClient.BeginSynchronizeDirectories(sourceDirectory, destinationDirectory, "*", sftpAsyncSynchronizeDirectoriesCallback, sftpState);
            if (asyncResult.IsCompleted)
But I'm not sure how to handle the state and callback...what I'd really like is to display back to my user a progress bar or some sort of indicator about the status of the directories as they're synchronized.

I've searched google/bing but not finding any results other than the method description.
Viewing all 2955 articles
Browse latest View live


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