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

New Post: IsConnected does not accurately reflect connection status?

$
0
0
Hey folks,

I have an odd issue and I'm trying to figure out if this is a bug or I'm just doing things wrong. I have code that opens a connection , writes a line to a ShellStream, and then monitors the output of the stream.

If I power off the host I'm connected to while I sit in a while loop waiting for stream data, no exception is thrown. Also sshClient.IsConnected reports true even though we (should) have lost connection with the server. It seems the sshclient object never becomes notified of the disconnect. Anyone know what I'm missing here? Thanks very much in advance

sshClient = new SshClient("ip", "user", "pass");
sshClient.Connect();

ShellStream stream = sshClient.CreateShellStream("MyStream", 600, 400, 800, 600, 100);
stream.WriteLine("someCommand")

bool keepReading = true;

while (keepReading && _sshClient.IsConnected)
{
// Some code to parse the output
}

New Post: Launch distant bash script

$
0
0
Hi!

I'm using SSH.NET to launch bash scripts (stored in my database) on distant computers.
using (SshClient client = new SshClient(execution.Host, 22, execution.User, key)) {
    client.Connect();

    SshCommand cmd = client.CreateCommand(execution.Script);
    cmd.Execute();

    execution.Result = cmd.Result;
    execution.ExitCode = cmd.ExitStatus;

    client.Disconnect();
}
execution.Script contains a script like, for instance:
# Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC)
findcpu() {
    grep 'model name' /proc/cpuinfo  | uniq | awk -F':' '{ print $2}'
}

findkernelversion() {
    uname -mrs
}

totalmem() {
    grep -i 'memtotal' /proc/meminfo | awk -F':' '{ print $2}'
}

echo "CPU Type : $(findcpu)"
echo "Kernel version : $(findkernelversion)"
echo "Total memory : $(totalmem)"
When i try to run this script directly on the distant computer, everything is fine. But with SSH.NET, I have an exit code of 1.

It works with smaller script, like for instance
T="$(date +%s)"

# Do some work here
sleep 2

T="$(($(date +%s)-T))"
So I'm a bit lost on this.. I just want to execute a script like a local user on the computer and to retrieve the output and the exit code...

Do you have any ideas?

Regards,

New Post: Sequential commands while retaining previous environment

$
0
0
I searched for an answer to my question but was not able to really find anything. I know the answer is probably simple, but...

I need to programmatically run commands sequentially while retaining the previous command's environment. I need to do this because these commands are generated on the fly based on logic on the client side. So if I call SshSession.CreateCommand twice to run these commands sequentially:
>cd someDirectory
>ls
Then it should list the contents of someDirectory. However I'm finding that each command is its own session and doesn't retain the previous environment.

I briefly looked at Shell and Session but I don't want to create an actual terminal window, it all needs to happen programmatically.

EDIT: I'm aware that I can run commands sequentially by separating them with ";". However this won't work because some of these commands are generated based on previous command results.

New Post: Channel sessions not cleaning up (Avoiding Memory Leaks)

$
0
0
Hours of experimentation in attempting to get SshCommand and/or ChannelSessions to properly dispose have led me nowhere. I obviously don't understand the full extent of the SshNet design (How session relates to SshCommand relates to Channel relates to ChannelSession).

At this time, unless there's some movement on suggestions, the only way I've found to actually get the leaks under control is to completely disconnect the SshClient and dispose of it. Then to re-create it and re-connect/authenticate to the server. Given the millions of commands I need to send during my long-term testing, this is not feasible for every command since OpenSsh will think it's a DDoS and throttle. Re-connecting every minute or so (With hundreds of SshCommand.Execute() calls in between) seems to keep the memory leak under some level of control at least. This is not an optimal solution of course, but it works.

New Post: Sequential commands while retaining previous environment

$
0
0
I do some pretty weird stuff through the SshCommand. It's tricky, but pretty much anything can be done:
r=0; for R in $(dmidecode -t 17 | grep Size|grep MB|awk '{print $2}'); do r=$[ $r + $R ]; done; echo $r MB
This sums up all the physical DIMM's reported in a server and produces a single output such as "32768 MB" which I can compare to via C#.

New Post: Launch distant bash script

$
0
0
function findcpu() { grep 'model name' /proc/cpuinfo  | uniq | awk -F':' '{ print $2}' ; }; function findkernelversion() { uname -mrs ;}; function totalmem() { grep -i 'memtotal' /proc/meminfo | awk -F':' '{ print $2}'; }; echo "CPU Type : $(findcpu)"; echo "Kernel version : $(findkernelversion)";echo "Total memory : $(totalmem)"
How's that? Works in Bash.

New Post: Sequential commands while retaining previous environment

$
0
0
Thanks for the reply. However this won't help me because essentially I need to make multiple calls from the client side, and the environment needs to be retained from one to the next call. Using SshCommand seems to start each command in its own new environment.

I've been having some luck with ShellStream although there are some bugs [(timeout != null)] and also I'm trying to do some proper formatting of the output. There are embedded \a and \b characters in there that screws with the formatting. From what I can tell, \a (which is bell), should also be considered a newline, and each \b (backspace) should delete a preceding character.

New Post: Sequential commands while retaining previous environment

$
0
0
ShellStream is the way to go if you want session persistence like you would see with an interactive ssh session (EX: putty). SshCommand acts more like plink. I haven't tried to use the ShellStream yet because it's still maturing (Also doesn't have expect functionality).

Created Unassigned: Bash problemusing ssh.net Library [1591]

$
0
0
Hi, here is my code
```
ssh.Connect();
var cmd = ssh.CreateCommand("ls -all");
var asynch = cmd.BeginExecute(delegate(IAsyncResult ar)
{
Console.WriteLine(cmd.Result);
}, null);

var cmd1 = ssh.RunCommand("bash /etc/motor.sh"); // Perform long running task
var asynch1 = cmd1.BeginExecute(delegate(IAsyncResult ar)
{
Console.WriteLine(cmd1.Result);
}, null);

while (!(asynch.IsCompleted && asynch1.IsCompleted))
{
Console.WriteLine("Waiting for commands to complete...");
Thread.Sleep(2000);
}
cmd1.EndExecute(asynch1);
cmd.EndExecute(asynch);
ssh.Disconnect();

Console.ReadLine();
```
The problem is that command "ls -all" works well but any bash command doesn't work..
Any suggestions ?

Thank you :)

New Comment on "Documentation"

$
0
0
I am unable to open the documentation..tried all the above mentioned solutions. Plz suggest what else to do.

New Post: "bad packet length xxxxx" error when retrieving only some secure FTP sub directory listings

$
0
0
I get an error "bad packet length xxxxx" when retrieving some sFTP sub directory listings. My connection is successful. FileZilla ftp client (default settings) has exact same issue with same dir's, but CoreFTP Lite (default settings) can list all dir's easily. If I move out a few files then I can list the sub directory's contents.

I heard it is because the sFTP server allows BOM as optional or something...

Are there any workarounds with SSH.NET C# library (latest version from https://sshnet.codeplex.com/).
using (var sftp = new SftpClient(s.Host, s.UserName, s.Password))
{
  foreach (var d in sftp.ConnectionInfo.Encryptions.Where(p => p.Key != "aes256-cbc").ToList())
    sftp.ConnectionInfo.Encryptions.Remove(d.Key);   // remove all Encryptions but the one listed above

  sftp.ConnectionInfo.Encoding = System.Text.UTF8Encoding.ASCII;
  sftp.Connect();  // always connects fine
  var files = sftp.ListDirectory("/SubDirectory");  // Error here for some sub dirs

New Post: SSH Server

$
0
0
Hi,

Does your component offer the ability to function as an SSH Server?

Thanks
Dan

New Post: Error: "Failed to open local file", upon downloading file

$
0
0
Hi,

I've created a basic SFTP client. I am successful in listing the directories and was also able to upload files to server. But, I am receiving the error "Failed to open local file", when I try to download file.

Below is the code that I used :
using (var sftp = new SftpClient(textBox1.Text, textBox2.Text, textBox3.Text))
 {
         folderBrowserDialog1.ShowDialog();
         string localFileName = folderBrowserDialog1.SelectedPath;
         sftp.Connect();
         string remoteFileName = sftp.WorkingDirectory + "\\" + "Demo.pptx";
         using (var file = File.Exists(localFileName + "\\" + "SampleFile.pptx") == false ? System.IO.File.OpenWrite(localFileName + "\\" + "SampleFile.pptx") : System.IO.File.Create(localFileName + "\\" + "SampleFile.pptx"))
         {
                 sftp.DownloadFile(remoteFileName, file);
         }
}
sftp.Disconnect();
Am I missing anything?

Created Unassigned: SSH through Proxy Problem [1601]

$
0
0
Hello guys,

im trying to connect through a proxy to my SSH server but i get an exception:
"__Renci.SshNet.Common.SshOperationTimeoutException: Socket read operation has time
d out
at Renci.SshNet.Session.SocketReadLine(String& response)
at Renci.SshNet.Session.ConnectHttp()
at Renci.SshNet.Session.Connect()
at Renci.SshNet.BaseClient.Connect()
at UAMT.MyClasses.RenciSSH..ctor() in D:\Project\MyClasses\RenciSSH.cs:line 36__".
In the Java Console i can see that it is connecting to Proxy but cant get connection to server. I placed the exe on a local pc and connected successfully to the SSH server without going through proxy. I tryed to connect with PuTTY using the same configuration (with proxy) and it worked fine. I also tryed another lib "Chilkat" and it worked fine (__without KeyAuthentification__) too but you have to buy a license to unlock the trial version and other libs dont support proxy functionality..... :(

the code im using:

ConnectionInfo connectionInfo = new ConnectionInfo("xx.xx.xx.xx", 22, "username", ProxyTypes.Http, "127.0.0.1", 18080, "", "", new PasswordAuthenticationMethod("username", "password"));

try
{
using (var ssh = new SshClient(connectionInfo))
{
ssh.Connect();

ssh.RunCommand("ls -l");

ssh.Disconnect();
}
}
catch (Exception ex)
{
Console.WriteLine();
}

Am i doing something wrong with ssh.net (maybe a flag that need to be set or something)?

Thanks in advance

killikax

New Post: Code to download SFTP files.

$
0
0
Hello,
I am new to to FTP concepts, my application is getting converted to SFTP. I wish update my existing Jelovic dll (FTP) with SSH.NET dll and need to write the code for the same.
Could you kindly provide me the exact code to download the files from the remote server along with all steps that are required to be done like replacing dll, functions etc.

Best Regards,
Chetan Navale | chetan.navale@hotmail.co.in | +91-9373364792

Commented Issue: SCP : Missing files when using DirectoryUpload [1382]

$
0
0
Hi,I have the following environment:- Win7 / 64- .NET 3.5- MPC-Target :OpenSSH_6.0p1, OpenSSL 1.0.0j 10 May 2012- SSH.NET commit 19813I want to upload a directory structure (recursive, depth = 2) from the PC to a MPC basedLinux remote system. The total amount of data is about 8MB with 23 files from55 bytes to 4MB.Calling mScp.Upload(new DirectoryInfo(localDir), remoteDir) does not result anyerror and the Uploading event shoes uploading all files. But after Upload() returnedThere are a random number of missing files on the target (between 1 and 5).It tried the same with a PC based Linux as target what resulted in the same behaviour(OpenSSH_5.8p1 Debian-7ubuntu1, OpenSSL 1.0.0e 6 Sep 2011). It seems theproblem is caused anywhere within SSH.NET.Does anyone have a solution?Extension:I tried to workaround by replacing Upload(new DirectoryInfo(...)) by several singlecalls of Upload(new FileInfo(...)). This worked but is too slow for my application.
Comments: ** Comment from web user: Schmid **

Hi Oleg,

you set the status to fixed and closed.
Which revision number fixed the bug?

Thanks
Ulrich

New Post: "bad packet length xxxxx" error when retrieving only some secure FTP sub directory listings

$
0
0
Update:
If there are 250 files or less in a subdirectory then I can retrieve a directory listing using FileZilla.
If there are 235 files or less in a subdirectory then I can retrieve a directory listing using the SSH.NET library for c#.

Created Unassigned: SCP : option not to create directory structure when uploading with a Stream [1605]

$
0
0
First, let me say that this library is really great! I had a requirement of accessing a private network through a SSH tunnel, and setting up port forwarding with your library was a breeze.

Now, I have a problem with `ScpClient.Upload`:
`ScpClient.Upload(FileInfo, string)` doesn't create the directory structure whereas `ScpClient.Upload(Stream, string)` does. Not only this is inconsistent, but I'm currently uploading a stream to a device that doesn't support directory creation, and I have no way to turn it off, unless writing to a temporary file first and using the FileInfo overload, which I would rather avoid.

Could you please add an option to create the structure? Thanks!

New Post: How to iterate through a directory listing by count, bytes, or a filter (list 100 files at a time for e.g.)

$
0
0
I am trying to see if there is a way to iterate through a secure FTP directory listing by count, bytes, or a filter or some other manner. I would like to only read the first 100 or so file names in a directory and then process them and continue with the next 100 or so files for example.

This is a workaround to calling “ListDirectory” and the main reason for this is because I have come up against some limits when there are too many files in a directory (more than 235). I found out there may be some issues with the FTP server I am using (SSH-2.01.36 Globalscape).

Commented Issue: SCP : Missing files when using DirectoryUpload [1382]

$
0
0
Hi,I have the following environment:- Win7 / 64- .NET 3.5- MPC-Target :OpenSSH_6.0p1, OpenSSL 1.0.0j 10 May 2012- SSH.NET commit 19813I want to upload a directory structure (recursive, depth = 2) from the PC to a MPC basedLinux remote system. The total amount of data is about 8MB with 23 files from55 bytes to 4MB.Calling mScp.Upload(new DirectoryInfo(localDir), remoteDir) does not result anyerror and the Uploading event shoes uploading all files. But after Upload() returnedThere are a random number of missing files on the target (between 1 and 5).It tried the same with a PC based Linux as target what resulted in the same behaviour(OpenSSH_5.8p1 Debian-7ubuntu1, OpenSSL 1.0.0e 6 Sep 2011). It seems theproblem is caused anywhere within SSH.NET.Does anyone have a solution?Extension:I tried to workaround by replacing Upload(new DirectoryInfo(...)) by several singlecalls of Upload(new FileInfo(...)). This worked but is too slow for my application.
Comments: ** Comment from web user: Schmid **

Hi Oleg,

I updated to revision 25006.
This did not fix the problem. Thus for me the bug is not fixed, yet.

Ulrich.

Viewing all 2955 articles
Browse latest View live


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