passing parameters from java to c# app goes wrong - c#

Hi I have a very annoying problem and I can't understand the reasons.
I have a c# form application which receives some args in main and uses them to connect to a device (ip,port,user,passw).
It also prints these arguments to see if they are correct.
Now if I call the exe with arguments from windows prompt all goes right.
But if I do the same thing from java using the Runtime exec() function the application starts,prints the correct arguments exactly in the same way as before BUT DOES NOT CONNECT!!
it's like arguments were wrong....any suggestion?? maybe exec passing is not the same as prompt??
I have debugged the process with vs and the variable are identical in both case but the connect function (which reminds to a third part library from device vendor)
code
public MyForm(string[] args)
{
InitializeComponent();
if (args.Length > 0)
{
this.IP = args[0];
this.PASSWORD = args[4];
this.ID = args[3];
this.PORT = args[1];
this.logTextArea.AppendText("Connection to " +
IP +":"+PORTA+" "+ID+" "+
PASSWORD+"\n");
} else set fixed values
JAVA
Runtime.getRuntime().exec("MyForm.exe IP PORT NOT_USED ID PASSW");

Related

C# multi-hop SSH (SSH through SSH)

I wrote a C# console program to connect from A (Windows 10, Console C# app) over SSH to B (Linux server) and from there on to C (Linux server), but I cannot connect from B to C (from A to B is ok).
When I connect from A over Windows terminal to B and from B's terminal to C, it works, so I proved that my credentials are fine.
I am using Renci.SshNet for C#
I created a class Server with a .Connect(), .Disconnect() and .Execute() extension methods and then the two class instances Broker and Destination
My code looks like:
if (Broker.Connect())
{
Broker.Execute("pwd");
if (Destination.Connect())
{
Destination.Execute("pwd");
Destination.Disconnect();
}
Broker.Disconnect();
}
The Ssh connection objets are created like var broker = new SftpClient("Ip", Port, "User", "Pass")
Then I am internally using broker.Connect() and broker.Disconnect() in Renci.Ssh.Net lib given methods
To broker.Execute("cmd") I basically do
var output = host.Ssh.RunCommand(str);
var res0 = output.ExitStatus;
var res1 = output.Result;
var res2 = output.Error;
My code works for the first part as I manage to get the output of Broker.Execute("pwd") but it does not connect on Destination.Connect() returning the message 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
My aim ist to multi-hop using an automated process from within C#: users must not interact with any console and I cannot modify nor store any files on the Linux sites
Any idea where the problem lies?
Thanks in advance,
I will like to summarize here how I ended solving this issue with the help of some valuable hints gathered over the net and from #jeb:
Open a cmd.exe console, type ssh userC#hostC -p portC-J userB#hostB - p portB (portB and portC can be ommited if they are the default port 22) and then you will be promped to enter passwordB and passwordC - in this order.
If the connection succeeded you will be then on the hostC console and will manage to do whatever you intend to do.
The code you'll need is:
static void RunSshHop(params string[] cmds)
{
try
{
using (Process p = new Process())
{
p.StartInfo = new ProcessStartInfo("cmd.exe")
{
RedirectStandardInput = true,
UseShellExecute = false,
//WorkingDirectory = #"d:\" // dir of your "cmd.exe"
};
p.OutputDataReceived += p_DataReceived;
p.ErrorDataReceived += p_DataReceived;
p.Start();
// way 1: works
foreach (var e in cmds)
p.StandardInput.Write($"{e}\n"); // cannot use 'WriteLine' because Windows is '\r' and Linux is '\n'
/* way 2: works as well
using (var sw = p.StandardInput)
{
foreach (var e in cmds)
if (sw.BaseStream.CanWrite)
sw.Write($"{e}\n"); // cannot use 'WriteLine' because Windows is '\r' and Linux is '\n'
}
//*/
p.WaitForExit();
if (p.HasExited)
{
Console.WriteLine($"ExitCode: {p.ExitCode}");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
And you can call it like this:
static void Main(string[] args)
{
RunSshHop(
"ssh userC#hostC -p portC-J userB#hostB - p portB",
"pwd",
//"...",
"ls"
);
}
To avoid having to enter the passwords for each host, you can also create an SSH key pair like this:
open cmd.exe console
type ssh-keygen -t rsa
choose path where to save the public and private keys that are to be generated (press enter to use the default destination)
copy the destination, you will need it later to get back yxour keys :-)
to manage an automated process, you have to leave the passphrase empty
-once the keys are generated, log onto the first host over ssh like ssh youruser#firsthost -p hostport (the -p hostport part can be ignored if port is the default 22)
type ssh-copy-id youruser#firsthost -p hostport
accept
repeat the process for the second host

Received Serial string doesn't enter the if -statement in Visual studio C# while the string seems to contain the right value

I have a device which sends "go" through serial communication. I want my application to act on that command, however it seems to have some kind of a bug.
The following code doesn't enter the if-statement, however when I print dataIN1 in a textbox is does print "go" in the textbox.
dataIN1 = serialPort1.ReadExisting(); // Read incoming data from serial port 1
if (dataIN1 == "go") { //if 'go' is send, check cBox and start program for programming
Weirdly the following change does work:
dataIN1 = serialPort1.ReadExisting(); // Read incoming data from serial port 1
textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = dataIN1;});
string test2 = textBox1.Text;
if (test2 == "go") { //if 'go' is send, check cBox and start program for programming
dataIN1 is a global string.
putting dataIN1 directly in test2 doesn't work as well.
I also tried:
string test = dataIN1;
string test2 = Test + dataIN1;
In case it sends g and o separately.
I don't want to use a textbox for it to work, does anyone has any ideas on how to tackle this problem?
This code is working
this code is not working

Get Linux server time from windows service c#

Is there anyway I can get linux server time from windows service given linux server IP ? I tried to use Cliwrap (https://github.com/Tyrrrz/CliWrap) and wrote the following function but it is not working as well:
public string GetLinuxServerTime()
{
using (var cli = new Cli("bash.exe"))
{
// Execute
var output = cli.Execute("ssh user#10.104.12.114 date");
return "abc";
}
}
Kindly suggest some another way.

Trying to pass stdin to a main method to evaluate code online

I am trying to build a web application to evaluate .Net code online (like http://ideone.com/)
I have managed to compile code with CodeDomProvider.
But I don't know how to pass stdin parameters to this function.
If a user writes this code in the textarea of my web application:
using System;
public class Test {
static void Main()
{
String t = "";
while (t != null){
t = Console.ReadLine();
Console.WriteLine(t+"OK");
}
}
}
I can Compile it with this code
CompilerInfo[] allCompilerInfo = CodeDomProvider.GetAllCompilerInfo();
//Tell the compiler what language was used
CodeDomProvider CodeProvider = CodeDomProvider.CreateProvider("C#");
//Set up our compiler options...
CompilerParameters CompilerOptions = new CompilerParameters();
var _with1 = CompilerOptions;
_with1.ReferencedAssemblies.Add("System.dll");
_with1.GenerateInMemory = true;
_with1.TreatWarningsAsErrors = true;
//Compile the code that is to be evaluated
CompilerResults Results = CodeProvider.CompileAssemblyFromSource(CompilerOptions, strCode);
Now I would like to manage generic parameters:
If I pass a sample parameter like this:
53
12
09
I would like the result of the compilation:
53OK
12OK
09OK
Do you know how to do this?
As I interpret the question, you are asking how to run and pass stdin command line data to an application that was compiled on your web server from code that a user typed into a text box. Avoiding the serious security concerns of doing such, what you want to do is launch the application using the System.Diagnostics.Process class, and specify RedirectStandardInput in the StartInfo property. Start by reading the MSDN docs on the Process class: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

Hostname scanning in C#

Iv'e recently started a new job as an ICT Technician and im creating an Console application which will consists of stuff that will help our daily tools!
My first tool is a Network Scanner, Our system currently runs on Vanilla and Asset tags but the only way we can find the hostname / ip address is by going into the Windows Console tools and nslookup which to me can be improved
I want to create an application in which I enter a 6 digit number and the application will search the whole DNS for a possible match!
Our hostsnames are like so
ICTLN-D006609-edw.srv.internal the d 006609 would be the asset tag for that computer.
I wish to enter that into the Console Application and it search through every hostname and the ones that contain the entered asset tag within the string will be returned along with an ip and full computer name ready for VNC / Remote Desktop.
Firstly how would I go about building this, shall i start the project of as a console app or a WPF. can you provide an example of how I can scan the hostnames via C#, or if there's an opensource C# version can you provide a link.
Any information would be a great help as it will take out alot of issues in the workpalce as we have to ask the customer to go into there My Computer adn properties etc and then read the Computer name back to use which I find pointless.
Regards.
Updates:
*1 C# Version I made: http://pastebin.com/wBWxyyuh
I would actually go about this with PowerShell, since automating tasks is kinda its thing. In fact, here's a PowerShell script to list out all computers visible on the network. This is easily translatable into C# if you really want it there instead.
function Find-Computer( [string]$assetTag ) {
$searcher = New-Object System.DirectoryServices.DirectorySearcher;
$searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry;
$searcher.SearchScope = 'Subtree';
$searcher.PageSize = 1000;
$searcher.Filter = '(objectCategory=computer)';
$results = $searcher.FindAll();
$computers = #();
foreach($result in $results) {
$computers += $result.GetDirectoryEntry();
}
$results.Dispose(); #Explicitly needed to free resources.
$computers |? { $_.Name -match $assetTag }
}
Here's a way you can accomplish this, although it's not the best. You might consider hitting Active Directory to find the legitimate machines on your network. The code below shows how you might resolve a machine name, and shows how to ping it:
static void Main()
{
for (int index = 0; index < 999999; index++)
{
string computerName = string.Format("ICTLN-D{0:000000}-edw.srv.internal", index);
string fqdn = computerName;
try
{
fqdn = Dns.GetHostEntry(computerName).HostName;
}
catch (SocketException exception)
{
Console.WriteLine(">>Computer not found: " + computerName + " - " + exception.Message);
}
using (Ping ping = new Ping())
{
PingReply reply = ping.Send(fqdn);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine(">>Computer is alive: " + computerName);
}
else
{
Console.WriteLine(">>Computer did not respond to ping: " + computerName);
}
}
}
}
Hope that helps...

Categories