How to make a echo command in a C# Application? - c#

So, I am making a hacking game, and in it you control a terminal. So far, I have done 'help' and 'cls' commands, that don't require parameters. But, for say a echo command, I need the computer to detect the keyword 'echo' and the rest of the text as what you want to 'echo'. How can I do this? Thanks for any help.

You can do something line this:
var input = Console.ReadLine(); //You might have this already in your code
if (input.StartsWith("echo "))
{
var text = input.Substring(5);
Console.WriteLine(text);
}
This checks to see if the input line starts with echo, and if it does, it prints to the console whatever is after the first 5 characters (which is the length of echo and one space)

Related

How to input command line arguments to a dotnet c# program using bash scripts?

I have a simple c# program that expects command line input (from Console.ReadLine()) when ran. There's a lot of inputs I have to provide, so I was wondering how I could automate this process. I currently have a shell script that attempts to do this, but it's not working.
#!/bin/sh
dotnet run #run the program
1 #input first argument (this failed so I tried echo 1 instead but no luck)
# <- rest of command line inputs on each line
Not really familiar with shell scripts, and I'm not fixed on this solution if you had another solution in mind. My OS is MacOS.
OK, so what I tried was this:
I made a little mcve-Console App: (dotnet 6)
var input = Console.ReadLine();
while( !string.IsNullOrEmpty(input) )
{
Console.WriteLine("User input: {0}", input);
input = Console.ReadLine();
}
Then I made a little input.txt
This is a Text.
This is another Text.
1
2
3
This is the final Text.
and finally run.sh as follows:
#!/bin/sh
dotnet run < "input.txt"
Output was
User input: This is a Text.
User input: This is another Text.
User input: 1
User input: 2
User input: 3
User input: This is the final Text.
/bin/sh is linked to dash shell in my case.
If in run.sh you replace "input.txt" with "$1", then you can call it with ./run.sh whateveryourinputfileis.txt to make a little more flexible.

C# - Consume pipeline like 'more' does (windows)

This seems trivial, but google only gives me powershell-related stuff and how to implement pipelines within programs.
I'm trying to consume input arguments from the (standard command processor cmd.exe for Windows 7, not powershell) command line pipeline on windows like 'more' does.
I'm trying to get this to work with two self-created .exe files:
randgen (creates a random number and writes it to the console)
wordwrite (the c# program that I want to consume this random number from the pipeline)
And using two common windows executables to test and model the behaviour:
echo (writes input to console)
more (displays output one screen at a time, can consume input from the pipeline)
Here's the current content of my Main function in wordwrite:
static void Main(string[] args)
{
string ouname = args[0];
DocWrite(ouname);
}
and the behaviour trying to naively pipe output from randgen into wordwrite:
D:\code>randgen | wordwrite
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at ADDoc.ADOUDoc.Main(String[] args)
(plus a popup telling me wordwrite.exe has stopped working)
Which is the behaviour of trying to consume a null array of arguments as input:
D:\code>wordwrite
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at ADDoc.ADOUDoc.Main(String[] args)
So the output of randgen isn't being read from the pipeline correctly as an argument to the wordwrite executable's args array (thanks #Peter Duniho for explaining the difference between stdin and how argument assignation works). Contrast that with the behaviour of the 'more' executable:
D:\code>randgen | more
56929227
That said, this 'pipeline-awareness' seems to be inherent to the 'more' executable itself, as another common windows executable, echo.exe, is just as pipeline-blind as wordwrite.exe:
D:\code>randgen | echo
ECHO is on.
D:\code>echo blah
blah
D:\code>echo
ECHO is on.
Here we can see that the attempt to use the pipeline is effectively the same as providing no arguments for echo.exe (contrasted in the middle with behaviour when an argument is provided).
Which suggests there is something I can add the the body of my Main function in wordwrite.exe to enable pipeline-consuming behaviour like the 'more' executable does. Does anyone know how this is done?
You can read data 'from the pipeline' (effectively, the stdin stream*) by using the Console.ReadLine() method, like so:
static void Main()
{
string ouname = Console.ReadLine();
DocWrite(ouname);
}
*The pipeline is a tool to direct the output of one process (stdout) to the input (stdin) of another one. So when you think of 'consuming input from the pipeline', think 'assign stdin to a variable that you then do stuff with'.
Reference:
C# Console receive input with pipe

Calling a Python script from C# - changing the script's filepath causes the program to not work

The following code works perfectly without flaw:
public partial class MainForm : Form
{
string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + #"\config\pathToPythonInterpreter.txt");
string pyWeather = #"C:\getWeather.py";
public MainForm()
{
InitializeComponent();
UpdateWeather();
}
public void UpdateWeather()
{
labelWeather.Text = PySharp.ExecutePy(pyInterp, pyWeather);
}
}
However, when I change the path to getWeather.py to not be in an arbitrary random location, like this:
string pyWeather = Directory.GetCurrentDirectory() + #"\scripts\getWeather.py";
Then my program no longer obtains the script's output. The script still works: I launched it using IDLE and it completed its function properly. When I call it using C#, the console opens, yet no output is obtained.
The Python script is the following:
from requests import get
from bs4 import BeautifulSoup as soup
r = get("http://www.ilmateenistus.ee/ilm/prognoosid/4-oopaeva-prognoos/")
parsed = soup(r.content, "html.parser")
container = parsed.find("div",{"class":"point kuusiku"})
print(str(container["data-title"]))
(It webscrapes my local weather)
PySharp.ExecutePy() can be viewed here
By far the strangest bug I've ever encountered. Any ideas?
EDIT 1: It seems that C# is indeed reading something from the script. It just appears that this something is.. nothing. I gave the label a default sample text, and after running the program, the label's text is simply changed to an empty string. Hope this incredible discovery helps somehow.
EDIT 2: The program fails to call the script correctly when its filepath contains spaces. For example:
C:\foo bar\testing\pyWeather.py
does not work!
Try surrounding the path that contains spaces with 2 double quotes.
For e.g.
string pyWeather = #"""C:\Users\[myname]\Documents\Visual Studio 2017\Projects\testing\testing\scripts\getWeather.py""";
Similarly, you can do string pyWeather = Directory.GetCurrentDirectory() + #"\scripts\getWeather.py"; followed by pyWeather = "\"" + pyWeather + "\"";.
I would want you to return the answer instead of printing. Printer is an I/O based solution to display. So it will work super fine with IDLE however it may not return results as you expected. I strongly believe this will solve your problem.
instead of printing please try return. I can give more support after trying this.
return(str(container["data-title"]))

Two things; console app run without .exe and args (C# console app)

Hi I would like to make my self able to maybe define my app into CMD by that I can type program instead of program.exe kind of like how ping works for example.
I also need help with arguments.
The point of my app is to send a get request to a local server evaling PHP fetching a result from it so I can easy quick debug things and calculate things ect from CMD.
So for example I have to do.
W:\Users\example>e.exe
echo "example";
.....
example
W:\Users\example>
Tow things with the above are very annoying. I need to enter e.exe and THAN I need to enter the code to eval :-/
How could I make it so I could just do
W:\Users\example>e echo "example";
.....
example
W:\Users\example
I really would like to get this working to make use faster + more simple ! this is a programmers way to calculating math :P
EDIT:
Below is the code;
static void Main(string[] args)
{
WebClient client = new WebClient();
Console.WriteLine("...");
string input = Console.ReadLine();
string php = client.DownloadString("http://192.168.1.50/test.php?exec="+input);
Console.WriteLine(".....");
Console.WriteLine("");
Console.WriteLine(php);
Console.WriteLine("");
}
I've tried to do "+arg[0] but does nothing at start :?
Don't type ".exe" as you don't need to type it... You may want to put your e.exe some place listed in PATH environment variable (or add path to the executable to the PATH).
Main(string[] args) are arguments passed to your program - use them whatever way you want. Note that they will be split on spaces, so you may need to String.Join them back if you need all arguments as one.
You can also use Environment.CommandLine if you need access to comple not parsed command line.

Changing environment variables of the calling process

This one seems trivial but the answer has eluded me for a few days now.
I have a Windows batch file, that calls a C# program to do an extra verification that cannot be done in a batch file. After the verification is complete I need to return a status and a string back to the calling shell.
Now the return value is trivial and my C# console app simply sets a return value (exit code if you will). And I thought the string will also be a piece of cake. I attempted to define a new shell variable using the:
Environment.SetEnvironmentVariable("ERR", "Some text");
This call should (and does) define a shell variable within the current process - that is the very C# process that created the variable. The value is lost as soon as the C# app terminates and the shell that created the C# app knows nothing about the variable. So... A call with no particular use... At all... Unless perhaps if I created a child process from the C3 app, perhaps it would inherit my variables.
The EnvironmentVariableTarget.Machine and EnvironmentVariableTarget.User targets for the SetEnvironmentVariable call don't solve the problem either, as only a newly created process will get these new values from the registry.
So the only working solution I can think of is:
write to stdout
write to a file
encode extra meaning into the return value
The first two are a bit ugly and the last one has its limitations and problems.
Any other ideas (how to set a shell variable in the parent process)? Maybe such shell variable modifications are a security concern (think PATH)...
Thank-you for your time.
I had the same problem as Ryan and the only thing that came to my mind as a work-around was to write a batch in error out to set the variable and to call it from the batch.
ConsoleApplication1.exe:
'put some sensible code here
'put result in variable myResult
Dim myResult As String = Guid.NewGuid().ToString("D").ToUpperInvariant()
Console.WriteLine("Normal output from the consonle app")
Console.Error.WriteLine("#ECHO OFF")
Console.Error.WriteLine("SET zzzResult={0}", myResult)
Test.cmd (the calling batch):
#ECHO OFF
:Jump to folder of batch file
PUSHD %~d0%~p0
:Define a temp file
SET zzzTempFile=%TEMP%\TMP%Random%.CMD
:Call .NET console app
ConsoleApplication1.exe 2>%zzzTempFile%
:Call the generated batch file
CALL %zzzTempFile%
:Clean up temp file
DEL %zzzTempFile%
:Clean up variable
SET zzzTempFile=
:Do something with the result
ECHO Yeah, we finally got it!
ECHO:
ECHO The value is "%zzzResult%".
ECHO:
:Clean up result variable
SET zzzResult=
:Go back to original folder
POPD
That should do the trick. And yes, I do know this is an old post and Ryan is solving other issues by now, but there might be still somebody else out there having the same problem...
What you are asking is to be able to arbitrarily write to the memory space of a running process. For good reason, this is not possible without SeDebugPrivilege.
Any of the three solutions you list will work. Stdout is the standard way to communicate with a batch script.
By the way, you're writing a Windows batch file. I'm pretty sure the ship has already sailed on "a bit ugly".
If you want to put a value of some output into a variable in the batch you can use the following construct:
FOR /F "usebackq tokens=4 delims=\[\] " %i IN (`ver`) DO set VERSION=%i
ECHO %VERSION%
Output on my OS:
6.1.7601
'usebackq' means we are using back quotes which gives the ability to use a fileset in the command quoted with double quotes. You may not need this. 'tokens' means the index in the resulting string array to select (it can be a range M-N). If you need to skip lines use 'skip=X'). 'delims' are the string separators to use (like string-Split() in .Net).
You will put your console app instead of 'ver' and adapt the delimiters and tokens to match your specific output. If you have more variables to fill you will need to make the if a bit more complex but that should make a good start.
My BAT is a bit rusty, but I think it's possible to retrieve the 'exit' code from processes you've run externally, perhaps via %ERRORLEVEL%. If that's the case, make sure to exit your program via
Environment.Exit(123); // where 123 = error code
You can't add any messages, so you'll have to do that in the .bat file.
If this isn't the case, stdout is probably the best way.
After stumbling on this myself as well recently, I came up with this approach. What I did is run the bat file using the Process class, i.e.
// Spawn your process as you normally would... but also have it dump the environment varaibles
Process process = new Process();
process.StartInfo.FileName = mybatfile.bat;
process.StartInfo.Arguments = #"&&set>>envirodump.txt";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// Read the environment variable lines into a string array
string[] envirolines = File.ReadAllLines("envirodump.txt");
File.Delete("envirodump.txt");
// Now simply set the environment variables in the parent process
foreach(string line in a)
{
string var = line.Split('=')[0];
string val = line.Split('=')[1];
Environment.SetEnvironmentVariable(var, val);
}
This seems to have worked for me. It's not the cleanest approach, but will work in a bind. :)

Categories

Resources