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
Related
I got this exception while I was trying to connect to rabbitmq. My app is running on .NET 5.
i dont use private vpc i have set the mq to public
Exception: None of the specified endpoints were reachable
Then I debugged the code and found that
Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host..
It tries to connect from my local machine. I was running rabbit mq locally and it was working fine but when moved to aws I got this exception.
Here are my settings for connecting to rabbitmq service
"Connections": {
"Default": {
"HostName": "myserver.amazonaws.com",
"UserName": "username",
"Password": "password",
"Port": 5671
}
}
i use event bus that attached with framework that i use to develop my project it is called abp framework here is my code to configure connection
Configure<BaseRabbitMqOptions>(options =>
{
options.Connections.Default.HostName = configuration["RabbitMQ:Connections:Default:HostName"];
options.Connections.Default.UserName = configuration["RabbitMQ:Connections:Default:UserName"];
options.Connections.Default.Password = configuration["RabbitMQ:Connections:Default:Password"];
options.Connections.Default.Port = configuration.GetValue<int>("RabbitMQ:Connections:Default:Port");
options.Connections.Default.AmqpUriSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
options.Connections.Default.VirtualHost = "/";
}
);
Update
i have set my connection to use ssl and now i get this exeption
AuthenticationException: The remote certificate was rejected by the provided RemoteCertificateValidationCallback.
I had the same problem and solved by specifying the server hostname in the SslOption.ServerName property like this:
var factory = new ConnectionFactory
{
UserName = userName,
Password = password,
VirtualHost = virtualHost,
HostName = hostname,
Port = port,
Ssl = new SslOption
{
Enabled = useSsl,
ServerName = hostname
}
};
The solution is based on the comment here by OP, I just wanted to add it as an answer for posterity.
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");
According to the documentation you should be able to get the credentials of the role assigned to the taskdefinition from within the running task (container) using the following url: http://169.254.170.2'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' where AWS_CONTAINER_CREDENTIALS_RELATIVE_URI resolves to a part of the url.
In my case in a log file I can see it resolves to:
http://169.254.170.2/v2/credentials/063b6cc6-0dc7-486e-ba0a-843a308b222d
But calling the API results in a time-out. What could be the reason the endpoint is not listening?
The container is running an ECS_OPTIMIZED image of windows-server-2019
private static async Task<string> GetCredentials(EnvironmentOptions opts)
{
try
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), $"http://169.254.170.2{opts.CredentailsUrl}"))
{
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
}
catch (Exception ex)
{
return $"{ex.Message} {ex.StackTrace}";
}
}
opts.CredentailsUrl = '/v2/credentials/063b6cc6-0dc7-486e-ba0a-843a308b222d' for example and is obtained from the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
The error message I get is: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I really should get back a json class like:
{
"AccessKeyId": "ACCESS_KEY_ID",
"Expiration": "EXPIRATION_DATE",
"RoleArn": "TASK_ROLE_ARN",
"SecretAccessKey": "SECRET_ACCESS_KEY",
"Token": "SECURITY_TOKEN_STRING"
}
At the Container Instance I run the following two commands from powershell:
Import-Module ECSTools
Initialize-ECSAgent -Cluster 'txp-dev-windows' -EnableTaskIAMRole -Version "latest"
And that resulted in this where the last line actually never continued (= hangs)
019-06-07T10:15:06Z - [INFO]:Runtime is already installed.
2019-06-07T10:15:06Z - [INFO]:Docker version 18.09.4, build c3516c43ef
2019-06-07T10:15:06Z - [INFO]:Configuring ECS Host...
2019-06-07T10:15:06Z - [INFO]:Checking Hyper-V Network adapter
2019-06-07T10:15:08Z - [INFO]:Default vEthernet adapter found for nat. Using this adapter.
2019-06-07T10:15:08Z - [INFO]:VMNetwork adapter found with mac: 00-15-5D-2B-E1-89
2019-06-07T10:15:08Z - [INFO]:Checking for network adatper with mac: 00-15-5D-2B-E1-89
2019-06-07T10:15:08Z - [INFO]:Network adapter found.
2019-06-07T10:15:08Z - [INFO]:Network adapter found with mac 00-15-5D-2B-E1-89 on interface 2
2019-06-07T10:15:08Z - [INFO]:Getting subnet info from docker...
2019-06-07T10:15:08Z - [INFO]:Docker subnet: 0.0.0.0/0
2019-06-07T10:15:08Z - [INFO]:Docker gateway:
WARNING: Waiting for service 'Docker Engine (docker)' to stop...
WARNING: Waiting for service 'Docker Engine (docker)' to stop...
WARNING: Waiting for service 'Docker Engine (docker)' to stop...
WARNING: Waiting for service 'Docker Engine (docker)' to stop...
WARNING: Waiting for service 'Docker Engine (docker)' to stop...
2019-06-07T10:15:22Z - [INFO]:Docker subnet: 172.31.16.0/20
2019-06-07T10:15:22Z - [INFO]:Docker gateway: 172.31.16.1
2019-06-07T10:15:24Z - [INFO]:Getting net ip address
2019-06-07T10:15:25Z - [INFO]:IP address not found.
Name Value
---- -----
PrefixLength 32
IPAddress 169.254.170.2
InterfaceIndex 2
2019-06-07T10:15:25Z - [INFO]:Creating new virtual network adapter ip...
New-NetIPAddress : Element not found.
At C:\Program Files\WindowsPowerShell\Modules\ECSTools\ECSTools.psm1:1370 char:28
+ $newIpOutput = New-NetIPAddress #IPAddrParams
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (MSFT_NetIPAddress:ROOT/StandardCimv2/MSFT_NetIPAddress) [New-NetIPAddress], CimException
+ FullyQualifiedErrorId : Windows System Error 1168,New-NetIPAddress
2019-06-07T10:15:25Z - [INFO]:Virtual network adapter ip created:
2019-06-07T10:15:25Z - [INFO]:Waiting for it to become available on the device...
Then I found this in te AWS documentation: IAM Roles for Task Container Bootstrap Script
Before containers can access the credential proxy on the container instance to get credentials, the container must be bootstrapped with the required networking commands.
So I added that bootstrap script to the container program when it starts:
string script = #"
$gateway = (Get-NetRoute | Where { $_.DestinationPrefix -eq '0.0.0.0/0' } | Sort-Object RouteMetric | Select NextHop).NextHop
$ifIndex = (Get-NetAdapter -InterfaceDescription 'Hyper-V Virtual Ethernet*' | Sort-Object | Select ifIndex).ifIndex
New-NetRoute -DestinationPrefix 169.254.170.2/32 -InterfaceIndex $ifIndex -NextHop $gateway
";
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(script);
PowerShellInstance.Invoke();
}
But it did not make a difference.
The exact reason for failing is unclear. It must have something to do that the EC2 instance is not correctly configured for the ECS Cluster. It was created manually and a powershell script of the initialization data connected it to the (Empty) Cluster. I had the to it that way because the Cluster creation wizards only allowed the use of Server 2016 AMI's. But to my surprise today it also allows the use of a Server 2019 AMI. Doing it with the wizard. The container code started to work.
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 have a Windows Service that retrieves messages from a RabbitMQ queue. The service works locally on a Windows 7 machine. When I install the service on a Windows 2008 server it does not work (and does not throw any errors). My ASP.net MVC app can publish messages to the same queue. Could there be a firewall or security issue here? Should I be retrieving messages from RabbitMQ differently than below?
public void PullFromQueue()
{
var connectionFactory = new ConnectionFactory();
using (var connection = connectionFactory.CreateConnection())
using (var channel = connection.CreateModel())
{
var consumer = new QueueingBasicConsumer(channel);
channel.ExchangeDeclare(ExchangeName, ExchangeType.Direct, true);
channel.QueueDeclare(QueueName, true);
channel.QueueBind(QueueName, ExchangeName, RoutingKey, false, null);
channel.BasicConsume(QueueName, null, consumer);
while (true)
{
try
{
var e = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var props = e.BasicProperties;
props.DeliveryMode = PersistentDelivery;
var businessObject = DeserializeBusinessObject(e.DeliveryTag, e.Body);
processBusinessObject(businessObject);
channel.BasicAck(e.DeliveryTag, false);
}
catch (Exception ex)
{
Log<RabbitMQWrapper>.Error("Error in pulling Business Object from Queue", ex);
}
}
}
}
Forgot about the GAC. When I installed the RabbitMQ.Client locally, it was placed in the GAC. Did not set the RabbitMQ.Client DLL to copy local. I find it curious that it did not generate a runtime error. I feel dumb.
I do the same thing and it works for me. Ensure you are running the service under NetworkService. Also the firewall could be an issue.
If you service just fail to start check the Event Logs (Application Event Logs) with Event Log Viewer.
If there is no clue, you should first determine what issue you are having right now (log4net can be usefull or simply just write exception to eventlog):
EventLog.WriteEntry(ex.Message + ", " ex.StackTrace);
If you are using RabbitMQ on your local machine with quest user, quest user can only access via loop-back! In this case, you should add different user like:
rabbitmqctl add_user testuser testpassword
rabbitmqctl set_user_tags testuser administrator
rabbitmqctl set_permissions -p / testuser ".*" ".*" ".*"
Regards...