Netstat focus on (find port) - c#

Im recently trying to execute the following line ;
string strCmdText;
strCmdText = "netstat -np TCP | find " + quote + number + quote + "";
System.Diagnostics.Process.Start("netstat.exe", strCmdText);
Logs.Write("LISTEN_TO(" + Registry_val1.Text + ")", strCmdText);
now what this has to do is basicly find all TCP ports that contain '80' in them and show them up in my custom-made log system that will make a logbook in my folder called;
LISTEN_TO(80)-{date_time}.txt
inside this .txt it should contain the command issued text, however all i get is a time.
i debugged this command as above, and unfortunately all i know is that the CMDtext is set correctly, and that my logging system works correctly, leaving me with no choice that NETSTAT may be closed as soon as the query is launched?
hopefully i provided anough information, as this is my first post.
Regards,
Co
Due to vague description, here's an other-sort same code i tried to do, however still remain getting only a time.
const string quote = "\"";
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.Arguments = "netstat -np TCP | find " + quote + number + quote + "";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
String output = p.StandardOutput.ReadToEnd();
Logs.Write("LISTEN_TO(" + Registry_val1.Text + ")", output);
basicly, you could see this as; textbox1.text = output; execpt now the output is being putten to a log file.

I don't understand why you use netstat in the first place. The .Net framework has a load of classes that give all kind of data, in this case IPGlobalProperties has the method you need.
var ip = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
foreach(var tcp in ip.GetActiveTcpConnections()) // alternative: ip.GetActiveTcpListeners()
{
if (tcp.LocalEndPoint.Port == number
|| tcp.RemoteEndPoint.Port == number)
{
Logs.Write(
String.Format(
"{0} : {1}",
tcp.LocalEndPoint.Address,
tcp.RemoteEndPoint.Address));
}
}
The benefit of using the build-in classes is the ease of shaping and selecting whatever you need and most important: you spare yourself and your user an out-of-process call and parsing of output.

You may try this:
strCmdText = "cmd /c \"netstat -np TCP | find " + quote + number + quote + "\"";
if this does not work, try first to use the command in a cmd prompt to make sure it returns data.
cmd /c "netstat -an | find "80"

Related

SCHTASKS Invalid Syntax in C# but working in CMD

I've got a command I'm trying to run through C# to get a list of tasks in CSV format from a bunch of computers.
To do this, I am using the SCHTASKS command with command redirection to a CSV. So I wrote this code in C# to do this for me:
string commandGetStatus = "schtasks";
string argumentsGetStatus = "/s:" + CompName +
" /fo:csv" +
" > \"" + #"\\BIG\OL\UNC\PATH\"+CompName+".csv" + "\"";
getLatestTaskStatus.StartInfo.FileName = commandGetStatus;
getLatestTaskStatus.StartInfo.Arguments = argumentsGetStatus;
getLatestTaskStatus.StartInfo.CreateNoWindow = true;
getLatestTaskStatus.StartInfo.RedirectStandardOutput = true;
getLatestTaskStatus.StartInfo.RedirectStandardInput = true;
getLatestTaskStatus.StartInfo.RedirectStandardError = true;
getLatestTaskStatus.StartInfo.UseShellExecute = false;
getLatestTaskStatus.Start();
It returns the output:
ERROR: Invalid syntax.
Type "SCHTASKS /?" for usage.
So I used StartInfo.FileName + " " + StartInfo.Arguments to print out the exact command that should be being executed. From there, I copy and pasted the command into CMD. Where it worked without a problem. This was the command + args:
schtasks /s:COMPUTERNAME /fo:csv > "\\BIG\OL\UNC\PATH\COMPUTERNAME.csv"
I'm not sure what the problem is at this point.
My Solution
Luaan was absolutely correct about the problem. The command prompt redirection operator,>, is not available without using Command Prompt. Fortunately, the solution was quote simple and easy to implement. I reduced the argument variable to:
"/s:" + CompName + " /fo:csv"
And with standard output being redirected, I simply used:
string output = process.StandardOuptut.ReadToEnd();
File.WriteAllText(#"\\UNC\File\Path\" + myfile + ".csv", output);
You explicitly disabled UseShellExecute - > is a shell operator, not something inherent to processes. It definitely isn't an argument. You need to read the output and write it out manually :)

How to rar/unrar with command line parameters

I've looked through the internet on how winrar's command line parameters work, and this is what I have so far
void LOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\WinRAR.exe";
p.StartInfo.Arguments = "rar a -p" + pw + " PL_LOCKED_ARCHIVE.rar " + fld;
p.Start();
}
void UNLOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\WinRAR.exe";
p.StartInfo.Arguments = "unrar x -p" + pw + " PL_LOCKED_ARCHIVE.rar";
p.Start();
}
However it doesn't seem to create any archive anywhere, with a test folder being C:\PicsAndStuff
The StartInfo you define results in running WinRAR.exe with command line:
C:\Program Files\WinRAR\WinRAR.exe unrar x -p pw PL_LOCKED_ARCHIVE.rar
That is of course wrong as you do not want to run WinRAR.exe with first argument being a reference to console version Rar.exe or UnRAR.exe. The result is most likely an error message because of invalid command rar respectively unrar as the first argument must be a or x for WinRAR.exe.
So first of all you need to correct StartInfo:
void LOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\Rar.exe";
p.StartInfo.Arguments = "a -p" + pw + " PL_LOCKED_ARCHIVE.rar " + fld;
p.Start();
}
void UNLOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\UnRAR.exe";
p.StartInfo.Arguments = "x -p" + pw + " PL_LOCKED_ARCHIVE.rar";
p.Start();
}
Further all commands and switches of console version Rar.exe are briefly explained when simply running Rar.exe without any parameter in a command prompt window. Also UnRAR.exe outputs a brief help if executed without any parameter.
Last but not least there is a complete manual for Rar.exe which of course can also extract files and folders from a RAR archive which makes additional usage of UnRAR.exe useless. The manual is text file Rar.txt in program files folder of WinRAR which you should read from top to bottom. I suggest to build the command line while reading it and test the command line first from within a command prompt window.
Note 1:
Rar.exe is shareware. Only UnRAR.exe is freeware.
Note 2:
GUI version WinRAR.exe supports more than console version Rar.exe and therefore the list of switches differ slightly. Complete documentation for WinRAR.exe can be found in help of WinRAR opened with Help - Help Topics or pressing key F1. Open in help on tab Contents the item Command line mode and read. WinRAR.exe is also shareware.
You need to encrypt both file data and headers.
According to Documentation (Command line mode > Switches > "-hp[pwd] - encrypt both file data and headers"):
This switch is similar to -p[p], but switch -p encrypts only file data
and leaves other information like file names visible. This switch
encrypts all sensitive archive areas including file data, file names,
sizes, attributes, comments and other blocks, so it provides a higher
security level.
This is how you can access to it using command line:
Syntax: rar a -hp[MyPassword] -r [filepath] [folderpath]
"C:\Program Files\WinRAR\WinRAR.exe" a -hp12345678 -r d:\zipProject d:\Project
C# Code:
void LOCK(string fld, string pw)
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files\WinRAR\WinRAR.exe";
p.StartInfo.Arguments = "rar a -hp" + pw + " PL_LOCKED_ARCHIVE.rar " + fld;
p.Start();
}

Issue when passing multiple arguments to an external exe program using c#

I have an exe file in which I am trying to pass arguments through c#. the code is as follows
class Class1
{
static void Main()
{
string[] arg;
arg = new string[3];
Process p = new Process();
p.StartInfo.FileName = #"D:\xxx.exe";
for (int i = 0; i < 3; i++)
{
arg[i] = Console.ReadLine();
}
p.StartInfo.Arguments = arg[0] + " " + arg[1] + " " + arg[2];
p.Start();
}
}
I open up a console and then write the arguments there. As soon as I am finished typing 3 arguments, I make a string out of the 3 arguments and then call Process.Start() with the arguments in the p.StartInfo.Arguments string. The exe file loads but it does not generate any output. The strange thing is that if I open the exe file from my computer and then write
Arg1.txt Arg2.txt Arg3.txt
and press enter the exe file generates the output. However the same arguments in the same style are currently being passed through C# code and it is not generating any output. I donot understand what I am doing wrong. There are multiple questions on StackOverflow about this, I know that, however they all suggest the same procedure as what I have done here. I have also tried giving arguments as
p.StartInfo.Arguments = "\"arg[0]\"\"arg[1]\"\"arg[2]\"";
but this also has not worked.
Try this:
p.StartInfo.Arguments = "\"" + arg[0] + " " + arg[1] + " " + arg[2] + "\"";
p.Start();
It is recomended to use "" when you use several parameters between gaps.
EDIT: No "\" have to be included if you type it ok. It is the escape character. See picture below.

Spawning command prompt app in CMD window in C#

I need to run a legacy app that is run from a cmd window using the Process class.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C \"C:\\MySys\\My2Com.exe –r " + Parameters.FullPath;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch (Exception e)
{
string sMsg = "Error copying the files to " + Parameters.FullPath + ".";
HandleErrorMsg(e, sMsg);
return;
}
The process My2Com.exe should run in the background, however, I consistantly get the message that a file, used when run from the cmd line with different flags, is missing. If I run the command as indicated in a cmd window, C:\MySys\My2Com.exe –r FullyQualPath, it works as expected. I have tried several different ways to set up the Process class without success.
Any suggestions would be appreciated.
Thank you.
Try this one -
startInfo.Arguments = "/C \"C:\\MySys\\My2Com.exe –r\" " + Parameters.FullPath;
will this work if you do the following
startInfo.Arguments = #"/C "C:\MySys\My2Com.exe /r" " + Parameters.FullPath +"\"";
keep in mind that if there are spaces in the filepath you need to wrap around """ for example if the filepath were like this #"""C:\Wolf Lair\WorkDeskTemp\"
notice the # and the """
you need to append the ending quotes to the string +"\""; after Parameters.FullPath;
You know why is it not working because
You haven't completed quotes
Try this:-
startInfo.Arguments = "/C \"C:\\MySys\\My2Com.exe\" –r \"" + Parameters.FullPath+"\"";
startInfo.Arguments = #"/C ""C:\MySys\My2Com.exe –r """ + Parameters.FullPath + "\"";
Also, see Sending commands to cmd prompt in C#. I'd recommended using some of the code from my answer there so that you can intercept the standard output and standard error to see what you're getting.

How to use CACLS in c# windows service

i want to block certain folder from users, using c# service. that means when you are starting the service though it is blocked or not, the final result is blocked folder. i have writen a code. but the responce is are you sure? please help to solve this
string Pathname = folder;
EventLog.WriteEntry(Pathname);
string Username = #"BUILTIN\Users";
string UserRights = "N";
if (Pathname == null || Pathname == "")
{
EventLog.WriteEntry("No File");
}
string CommandLine = '"' + System.IO.Path.GetFullPath(Pathname) + '"' + " /C ";
CommandLine += #" /T ";
CommandLine += #" /P " + Username + ":" + UserRights;
Process p = new Process();
p.StartInfo.FileName = "cacls.exe";
p.StartInfo.Arguments = CommandLine;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
p.StartInfo.CreateNoWindow = true;
p.Start();
string Response = p.StandardOutput.ReadToEnd();
EventLog.WriteEntry(Response);
if (Response == null || Response == "")
{
EventLog.WriteEntry("Error");
}
Don't call the command line cacls utility, instead use the .NET API to change permissions. Invoking command line utilities should always be seen as a last workaround for performing tasks. It is much better to access an API directly that is meant for programmatic access.
Directory.GetAccessControl(string) gets the current ACL.
Directory.SetAccessControl(string, DirectorySecurity) sets the ACL.
Generally when working with ACLs it's better to work only with granting rights and not use deny flags at all. Denying BUILTIN\Users is very broad and that deny will overrule any grant made to any user. It is better to construct an ACL that does not grant any rights to normal users and only give rights to the specific users that should have access.
You are redirecting the standard input for the CACLS process.
So you need to feed the process with your input (Like a stream.Writeline("Y");)
Look at this sample from MSDN
StreamWriter myStreamWriter = myProcess.StandardInput;
myStreamWriter.Writeline("Y"); // Could it be localized ??? -->Oui, Ja, Sì etc...
myStreamWriter.Close(); // This seems to be is important.....

Categories