Calling a process from a while loop - c#

I am trying to delete and rebuild an encrypted password file. I am able to create the file and add usernames and encrypted passwords if I run the commands manually on the server within a command window. But I get nothing if I try to run this code from within my C# web api controller. The delete line works, but the first Process.Start line fails, and it never makes it to my while loop.
System.IO.StreamReader pass2 = new System.IO.StreamReader(pass);
File.Delete("C:\\inetpub\\wwwroot\\password\passMD5.txt");
Process.Start("C:\\inetpub\\htpasswd.exe -bc C:\\inetpub\\wwwroot\\password\\passMD5.txt sm88555 sm88999");
while ((line = pass2.ReadLine()) != null)
{
un = line.Substring(0, 6);
pw = line.Substring(7, 6);
Process.Start("C:\\inetpub\\htpasswd.exe -b C:\\inetpub\\wwwroot\\password\\passMD5.txt " + un + " " + pw);
}
pass2.Close();

Related

WPF: unable to map network drive for all users

I'm trying to create a function for an application to automatically copy over specific files during the final stage of a job. The only issue here is that the copy location is a protected share drive and uses a separate login instead of being validated by the active directory so I've got to do a bit of a workaround to get File.Copy() working. My workaround has been to call the built in net.exe utility and passing a command line argument that points to the share drive to open up a connection to the drive then using File.Copy() to get the file where it needs to go then deleting the connection. The issue at hand is that this works great on my computer but when anyone else on the team runs the same program a "Logon failure: unknown user name or bad password" is thrown. I'm at a bit of loss as to why this would happen since the username and password are static and not being changed and everyone on the team has the same network permissions I do. Here is the WPF/C# code I'm using to do this:
try
{
string mrdfDropPath = #"dropPathHere";
string MRDFPath = #"storePath\test.xml";
string command = #"use " + mrdfDropPath + #" /user:CORP\Username Password";
Process.Start("net.exe", command);
File.Copy(MRDFPath, mrdfDropPath + "test.xml");
string command2 = #"use " + mrdfDropPath + #" /delete";
Process.Start("net.exe", command2);
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(mrdfDropPath + "test.xml" + "," + File.GetLastWriteTime(MRDFPath).ToString());
writer.Close();
}
catch (Exception e)
{
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(e.Message);
writer.Close();
}
Like I said this works as expected during debug and when I run the application, but for anyone else it is throwing the error.

C# delete line from file over SSH

I'm using Renci SshNet to access a file via SSH from a C# program that I'm writing.
Using data from my app I create a line in a text file as below.
sshclient.Connect();
string data1 = textBox1.Text + ":";
string data2 = textBox2.Text + ":";
string ip = "${SSH_CLIENT%% *}" + ":";
string data = ("\necho " + ip + data1 + data2 " >> file.txt");
var cmd = sshclient.CreateCommand(data);
cmd.Execute();
sshclient.Disconnect();
The above code results in a line being added to the text file when I start my app as below, which is exactly what I want.
123.456.789.000:data1:data2:
I would like to delete the line from the text file when my app closes, but so far I'm not having much luck.
Below is what I've tried...
sshclient.Connect();
textBox3.Text = new WebClient().DownloadString("http://icanhazip.com");
string ip = textBox3.Text;
string del = ("sed -i '/" + ip + "/ d' file.txt");
var cmd = sshclient.CreateCommand(del);
cmd.Execute();
sshclient.Disconnect();
The textbox does show the ip correctly when it's read from the web and added to the textbox.
But if I use the command above, the line is not deleted unless I manually type the ip into the textbox.
I have also tried
string del = ("sed -i '/${SSH_CLIENT%% *}/ d' file.txt");
What am I doing wrong?
It seems the IP had a space at the end which I couldn't see in the text box.

get Redirecting output from plink

I am currently trying to write a function that runs plink and captures the output from that process. When I try StandardOutput I get nothing and when I try StandardError I get "Unable to read from standard input: The handle is invalid." I can only assume that this means I am trying to read while plink is waiting for input. I am also passing my command via a text file called apCommands.txt. When I run this command manually it works and gives me the required output, I just can't figure out why I can't redirect that output so I can store it in a results file. Here is the code I have right now.
string pArgs = "-m \"" + ABSPATH + "\\apCommands.txt\" -ssh myHost -l user -pw password";
string output;
if (File.Exists(ABSPATH + "\\apTest.txt"))
File.Delete(ABSPATH + "\\apTest.txt");
StreamWriter apTest = new StreamWriter(ABSPATH + "\\apTest.txt");
Process runAP = new Process();
ProcessStartInfo apInfoStart = new ProcessStartInfo(ABSPATH + "\\plink.exe");
apInfoStart.Arguments = pArgs;
apInfoStart.RedirectStandardOutput = true;
apInfoStart.CreateNoWindow = true;
apInfoStart.UseShellExecute = false;
runAP.StartInfo = apInfoStart;
runAP.Start();
output = runAP.StandardOutput.ReadToEnd();
runAP.WaitForExit();
apTest.WriteLine("Standard Output");
apTest.WriteLine(output);
apTest.Close();
runAP.Close();
Thanks,
To solve this error, use apInfoStart.RefirectStandardInput = true;
see also: https://social.msdn.microsoft.com/Forums/vstudio/en-US/697324fa-6ce6-4324-971a-61f6eec075be/redirecting-output-from-plink
You can do the same for StandardOutput and StandardError

Inconsistent results during debugging - Web API

I have some code that uses a library for a product called Fusion Pro. Based on some config and data files it will generate a PDF file. I have been getting consistent result of a complete lack of output without any thrown exceptions. However when debugging I have been able to get the PDF to generate by attaching the debugger to the code running in my local IIS and stepping through line by line. Nothing is consistent though. It seems to have a higher success rate if I use F11 instead of F10 and going "slow but steady" through each line. Unfortunately it doesn't always produce a PDF even with stepping through the code.
I have never experienced code behaving so inconstantly with the same inputs each time.
The only other relevant bits of information is this code is working in another asmx service without issue, it is running under a specific domain account (requires special security), and it is running in 32bit mode.
DLQueueClient client = new DLQueueClient();
DLQueueJob vdpQueueJob = new DLQueueJob();
string fileName = message.OutputFilePath;
var dataFilePath = CreateDataFile(fileName, message.DefFilePath, message.VariableDataContent, message.QTY);
var pdfFilePath = Path.Combine(new[] { message.OutputFilePath, dataFilePath.Replace(".txt", ".pdf") });
vdpQueueJob.Priority = priority;
vdpQueueJob.Queue = queueName;
string cmd = "\"" + Settings.FusionProExe + "\" \"" + dataFilePath + "\" \""
+ message.DiffFilePath + "\" \"" +
(isProof ? message.ProofConfigFilePath : message.PrintConfigFilePath) + "\" \""
+ pdfFilePath + "\"";
vdpQueueJob.CommandLine = cmd;
client.ConnectRemote(Settings.FusionProServer, Settings.FusionProUser, Settings.FusionProPassword, Settings.FusionProTimeout);
client.SubmitJob(vdpQueueJob, Settings.FusionProTimeout, true);
return pdfFilePath;

Attempting Simultaneous File Operations

I am attempting to create an ASP.NET 4.0 website (C#) that does the following: after the user clicks a button, take user inputs (from text boxes) and call a Powershell script on the server. The Powershell script output is logged to a textfile on the same machine. The script executes some stored procedures on a SQL server. Once the script is done executing, the page reads the contents of the log file and returns them in the page. The reason I log this as I do is because I need to capture the "verbose" output of these operations.
The problem I am having is that the whole set of commands that are run after the user clicks the button is queued if another user has the site open and is attempting the same operation. I am not clear as to why this happens. When run outside of the website, the Powershell scripts execute in parallel. The log files that the application writes to use a timestamp and user inputted information to ensure that they are different depending on who is inputting the info.
Here is the code that is executed when the button is clicked:
protected void Test_Click(object sender, EventArgs e)
{
// Get the current date/time to use a timestamp for the log file
DateTime curDate = DateTime.Now;
string logFileName = "D:\\test1\\logs\\" + curDate.Year + curDate.Month + curDate.Day +
curDate.Hour + curDate.Minute + curDate.Second + curDate.Millisecond + "_" +
TextBox1.Text.Replace("\\", "_") + "_Test.txt";
// Clean the Result TextBox
ResultBox.Text = string.Empty;
// Initialize PowerShell engine
var shell = PowerShell.Create();
// Add a script to the PowerShell shell object that will execute the instructions with the given input
shell.Commands.AddScript("powershell.exe -file D:\\test1\\ps_script0.ps1 '" + TextBox3.Text + "' '" +
TextBox1.Text + "' '" + TextBox2.Text + "' '" + TextBox4.Text + "' > " + logFileName);
// Execute the script
shell.Invoke();
// Create a StreamReader object to read the results of the script instructions and then store the file's contents in a string
StreamReader sr = File.OpenText(logFileName);
String results = sr.ReadToEnd();
results = results.Replace("VERBOSE: ", "");
sr.Close();
// Set the text of the result box to the string that was read in
ResultBox.Text = results;
}
I am hoping to find out if there is information I can read about allowing multiple users to click this button, and have the backend script run simultaneously for each of them. I looked into asynchronous pages and threads, but I don't think this is necessary in my case since each user's page should have its own thread. Any help here is much appreciated. Thanks!

Categories

Resources