Trying to use SSH.NET to connect to the Cisco wireless controller and add a mac address to it. When I debug my code I am getting a true on the IsConnected property of the client, but when I log onto the controller itself and do a "Show loginsession", I am not seeing the supposed connection being listed.
Also, when I get to var result = client.RunCommand(comman.ToString()).Result; the code just hangs with no response at all. Have left for several minutes and does not timeout or return any sort of error.
Picture of PuTTY session when executing above line
It does not matter what we use for "login as".
public WebAPIEndPoint Put(WebAPIEndPoint console)
{
var auth = new PasswordAuthenticationMethod("UserName", "Password");
var connectionInfo = new ConnectionInfo(hostIP, 22, "UserName", auth);
using (var client = new SshClient(connectionInfo))
{
client.Connect();
var command =
client.CreateCommand("config macfilter add 00:17:ab:ea:d4:aa 5 0 Testing1234");
var result = client.RunCommand(comman.ToString()).Result;
Console.WriteLine(result);
client.Disconnect();
return console;
}
}
When running plink user#host config macfilter add 00:17:ab:ea:d4:aa 5 0 Testing1234, I get:
FATAL ERROR: Server refused to start a shell/command.
Your server does not seem to support SSH "exec" channel. So you cannot use CreateCommand/RunCommand.
You have to use a "shell" channel (SshClient.CreateShell or SshClient.CreateShellStream). This is normally not recommended for a command automation. Even more so with SSH.NET, which does not even allow your to turn off a pseudo terminal for the "shell" channel. This brings lots of nasty side effects, particularly with "smart" shells on Linux. But with devices likes yours, it might be bearable and the only solution anyway.
ShellStream shellStream = client.CreateShellStream(string.Empty, 0, 0, 0, 0, 0);
shellStream.Write("username\n");
shellStream.Write("password\n");
shellStream.Write("config macfilter add 00:17:ab:ea:d4:aa 5 0 Testing1234\n");
Related
When trying to connect to a Mosquitto MQTT queue running locally, I get the following error.
Unhandled exception. System.AggregateException: One or more errors occurred. (The client has been disconnected while trying to perform the connection)
---> System.Net.Mqtt.MqttClientException: The client has been disconnected while trying to perform the connection
at System.Net.Mqtt.Sdk.MqttClientImpl.ConnectAsync(MqttClientCredentials credentials, MqttLastWill will, Boolean cleanSession)
I am using the default options when setting up the System.Net.Mqtt.MqttClient.
var config = new MqttConfiguration() {
Port = 1883
};
var client = MqttClient.CreateAsync("localhost", config).Result;
var sessionState = client.ConnectAsync(
new MqttClientCredentials(clientId: "camerasim")).Result;
The following errors show up in the Mosquitto MQTT log.
1644497589: New connection from 172.17.0.1:56792 on port 1883.
1644497589: New client connected from 172.17.0.1:56792 as camerasim (p2, c0, k0).
1644497589: Bad socket read/write on client camerasim: Invalid arguments provided.
The error you are seeing is most likely the result of a change made in Mosquitto 2.0.12:
Fix max_keepalive not applying to MQTT v3.1.1 and v3.1 connections. These clients are now rejected if their keepalive value exceeds max_keepalive. This option allows CVE-2020-13849, which is for the MQTT v3.1.1 protocol itself rather than an implementation, to be addressed.
A change made in 2.0.9 also comes into play:
Fix max_keepalive option not applying to clients connecting with keepalive set to 0. Closes #2117.
These changes were made to address an issue with the MQTT protocol itself which permits a denial of service attack (CVE-2020-13849).
The default value for max_keepalive is 65535 so this change means that attempting to connect with keep alive set to 0 (meaning no keepalive) will fail unless mosquitto.conf specifies max_keepalive 0. Unfortunately the error logged (Bad socket read/write on client XXXXXYYYYY: Invalid arguments provided.) does not really highlight the cause.
There are two available solutions:
Specify max_keepalive 0 in mosquitto.conf (Mosquitto 2.0.13 or later).
When connecting specify a keep alive between 1 and 65535. In xamarin/mqtt this means adding KeepAliveSecs to your config; this defaults to 0.
Note that setting KeepAliveSecs = 1 (as per your answer) will allow you to connect but is probably a little short for most users (KeepAliveSecs = 60 may be more appropriate). e.g.
var configuration = new MqttConfiguration {
Port = 1883,
KeepAliveSecs = 60,
WaitTimeoutSecs = 2,
};
I realise that you have already found a solution to this but as it's likely to affect others I thought it was worth explaining the root cause of the issue. Many MQTT libraries default keep alive to 0 so will be impacted (e.g. Go Paho had an issue logged).
I was able to successfully make a connection by changing the default KeepAliveSecs property when setting up the MqttConfiguration.
var config = new MqttConfiguration() {
KeepAliveSecs = 1,
Port = 1883
};
I am trying to make request to my server by MagicOnion protocol (it uses transport from gRPC, but deffrent serialization protocol, message pack instead of protobuf).
An simple test client app, working under net5.0 is executing code like this:
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
var address = $"http://{ServerUrl.Host}:5002";
using var channel = GrpcChannel.ForAddress(address);
var myServiceClient = MagicOnionClient.Create<IMyService>(channel);
var result = await myServiceClient.GetMyData();
...and recieves response succesfully. But if I try to execute the same code on Android app, I am seeing this exception message on server logs:
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2ConnectionErrorException: HTTP/2 connection error (PROTOCOL_ERROR): Invalid HTTP/2 connection preface.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ParsePreface(ReadOnlySequence`1& buffer, SequencePosition& consumed, SequencePosition& examined)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.TryReadPrefaceAsync()
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Connection.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
With logs and traffic dump I can see that the client on .Net 5 uses HTTP/2, but on Android - HTTP/1.1. As I can see, this is the only deifference between requests.
So, how can I make Android (API30, monoandroid10.0) client use HTTP/2?
The resolution is to use another gRPCC implementation lib - Grpc.Core. It provides GrpcChannel class wich is compatible with MagicOnion.
In my case, the library didn't work immediately, throwing the error about libgrpc_csharp_ext loading trouble. To solve this, you also have to add pacakge Grpc.Core.Xamarin.
The usage example:
var channel = new Grpc.Core.Channel(ServerUrl.Host, 5002, Grpc.Core.ChannelCredentials.Insecure);
var myServiceClient = MagicOnionClient.Create<IMyService>(channel);
var result = await myServiceClient.GetMyData();
I have a C# application that needs to run certain commands on a piece of hardware over SSH. The application is using SSH.Net to make the connection, send the command, and the read the result. I have this working if I connect to my local machine using OpenSSH. Finally, I wanted to go a step further and setup my own SSH server so I could simulate multiple hardware devices at one time (need to simulate having 50+ devices to SSH into).
For this I have setup a simple SSH server using nodejs and the ssh2 package. So far I have the client connected, authenticated (all connections are accepted for now), and I can see a session object being created. Although where I'm hitting a wall is with the execution of commands sent by the client. I noticed that ssh2 has an event for exec on the session object but this never seems to trigger (regardless of what i put in SSH.Net's ShellStream).
The C# client code that initiates the connection is the following (command is already defined that the command string to be executed):
using(SshClient client = new SshClient(hostname, port, username, password))
{
try
{
client.ErrorOccurred += Client_ErrorOccurred;
client.Connect();
ShellStream shellStream = client.CreateShellStream("xterm", Columns, Rows, Width, Height, BufferSize, terminalModes);
var initialPrompt = await ReadDataAsync(shellStream);
// The command I write to the stream will get executed on OpenSSH
// but not on the nodejs SSH server
shellStream.WriteLine(command);
var output = await ReadDataAsync(shellStream);
var results = $"Command: {command} \nResult: {output}";
client.Disconnect();
Console.WriteLine($"Prompt: {initialPrompt} \n{results}\n");
}
catch (Exception ex)
{
Console.WriteLine($"Exception during SSH connection: {ex.ToString()}");
}
}
The nodejs server code that set ups the ssh2 server is following:
new ssh2.Server({
hostKeys: [fs.readFileSync('host.key')]
}, function(client) {
console.log('Client connected!');
client.on('authentication', function(ctx) {
ctx.accept();
}).on('ready', function() {
console.log('Client authenticated!');
client.on('session', function(accept, reject) {
var session = accept();
// Code gets here but never triggers the exec
session.once('exec', function(accept, reject, info) {
console.log('Client wants to execute: ' + inspect(info.command));
var stream = accept();
stream.write('returned result\n');
stream.exit(0);
stream.end();
});
});
}).on('end', function() {
console.log('Client disconnected');
});
}).listen(port, '127.0.0.1', function() {
console.log('Listening on port ' + this.address().port);
});
I have seen various ssh2 client examples invoking a client.exec function but I was assuming that it did not matter that my client was not using the ssh2 node package. Is there something that I'm missing here?
The "exec" Node.js server session event is for "non-interactive (exec) command execution". By which they most likely mean SSH "exec" channel (which is intended for "non-interactive command execution").
To execute a command using "exec" SSH channel in SSH.NET, use SshClient.RunCommand.
On the contrary SshClient.CreateShellStream uses SSH "shell" channel, which is intended for implementing an interactive shell session.
For that, you need to handle "shell" Node.js server session event.
I'm trying to work through the hello world example on the Neo4j .Net driver page but every time I try to run the example, it spins for a while and then throws an exception:
Neo4j.Driver.V1.ServiceUnavailableException: 'Failed after retried for
5 times in 30000 ms. Make sure that your database is online and retry
again
I've confirmed my database is running as I can see it through the neo4j browser running at localhost:7474. I'm trying to create the connection as follows
// Invocation in Main method
using (var greeter = new HelloWorldExample("bolt://localhost:7474", "neo4j", "neo4j"))
{
greeter.PrintGreeting("Hello, World");
}
...
// Constructor for HelloWorldExample, and where it's getting hung
public HelloWorldExample(string uri, string user, string password)
{
_driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
}
I've tried several different variants of the URI (such as using port 7687, like the example says, even though that's not where my instance is running) as well as trying to use http instead of bolt as the protocol (which threw a completely different error, saying that's not allowed) to no avail. Anyone know what I might be missing?
You are using the wrong port, that is the UI port. You need to connect to port 7687 (if you are using the defaults, which I assume you are)
using (var greeter = new HelloWorldExample("bolt://localhost:7687", "neo4j", "neo4j"))
{
greeter.PrintGreeting("Hello, World");
}
Again, it supposed to be simple, but wasn't able to find any documentation about it
In my previous question I had a problems with running rabbitmq container in docker. It has been solved, but now another one appeared
Container was created with this line
docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 rabbitmq:3-management
I was trying to create a simple console application to check how message sending is working (from base tutorial):
var factory = new ConnectionFactory()
{
HostName = "localhost",
Port = 15672
};
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("Test", false, false, false, null);
var mess = new RepMessage()
{
ConnectionString = "TestingString",
QueueID = 5
};
var jsonified = JsonConvert.SerializeObject(mess);
var messBody = Encoding.UTF8.GetBytes(jsonified);
channel.BasicPublish("", "Test", null, messBody);
Console.WriteLine(string.Format("Message with ConStr={0}, QueueID={1} has been send", mess.ConnectionString, mess.QueueID));
}
}
And result is, its not working.
I am receiving exception None of the specified endpoints were reachable and inner exception as connection.start was never received, likely due to a network timeout
If I remove port, then my inner exception transforms in No connection could be made because the target machine actively refused it 127.0.0.1:5672
What am I missing, is is this example not supposed to work with docker?
Port 15672 is a port of rabbitmq management plugin web interface. When you are sending message to rabbit - you need to connect to different port (by default - 5672). So change your code to connect to that port and map it in docker via -p 5672:5672.
In your particular case docker command would look like this
docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 -p 5672:5672 rabbitmq:3-management