Running .cmd file by C# - c#

I am using the mentioned code to run a cmd file. It is working properly in my local machine. However when I am running in a remote machine windows security warning is coming. How can i bypass that security warning. Any help?
string[] newFilePath = Directory.GetFiles(workingDir, "*.cmd");
foreach (var n in newFilePath) {
finishedOld = false;
Process p = new Process();
p.StartInfo.FileName = string.Format("\"" + n + "\"");
p.Start();
p.WaitForExit();
p.Dispose();
finishedOld = true;
}

Related

Win C#: Install/Run app as administrator without UAC prompt

I have a requirement where application (app1) needs to install / run another application (app2) on user system in non production hours without UAC prompt. I think I can do it with windows service which will elevate my application 1 (app1) which will install my app 2. I worte below code in my console app which will called by windows service :
SecureString ss = ConvertStr.ConvertToSecureString("****");
DirectoryInfo d = new DirectoryInfo(userDownloadFolder);
string[] extensions = new[] { ".bat", ".exe" };
FileInfo[] Files =
d.GetFiles()
.Where(f => extensions.Contains(f.Extension.ToLower()))
.ToArray();
foreach (FileInfo file in Files)
{
if (File.Exists(d.FullName + file.Name))
{
try
{
var proc = new Process();
proc.StartInfo.FileName = d.FullName + file.Name;
proc.StartInfo.Domain = "****";
proc.StartInfo.UserName = "**********";
proc.StartInfo.Password = ss;
proc.StartInfo.Verb = "runas";
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
var exitCode = proc.ExitCode;
proc.Close();
}
catch (Exception ex)
{
Logger.WriteToFile(ex.Message);
}
}
else
{
Logger.WriteToFile("File does not exists");
}
Console application runs but it gives Access is denied. But when I tried to install /run by manually right clicking app with user Id & password in UAC prompt it works. Any idea any other way to implement this.

How to use SFTP with .pem file in C#.net?

Problem: I am using C# .net platform to SFTP a file to remote host with a key file/.pem file and no password.
C#.net source code:
ProcessStartInfo p = new ProcessStartInfo
{
FileName = "sh",
Arguments = "upload.sh " + file
};
p.RedirectStandardOutput = true;
p.UseShellExecute = false;
p.CreateNoWindow = true;
Process proc1 = new Process();
proc1.StartInfo = p;
proc1.Start();
string result = proc1.StandardOutput.ReadToEnd();
log.InfoFormat(result);
upload.sh:
sftp -i testsftp-key testsftp#sftp.xxx-xxx.com
put filename
here
testsftp-key :.pem filename(key file),
testsftp :username,
sftp.xxx-xxx.com :host address.
filename :file to be uploaded
File is not getting uploaded when exe is executed by rrot user/cronjob. Executing using non-root user like pi uploads the file.
Permissions are 777 for all.
Error:
permission denied
How to solve this permission issue?
I found an answer to this:
ProcessStartInfo p = new ProcessStartInfo
{
FileName = "sh",
Arguments = "/home/pi/../upload.sh " + file
};
p.RedirectStandardOutput = true;
p.RedirectStandardError = true;
p.UseShellExecute = false;
p.CreateNoWindow = false;
Process proc1 = new Process();
proc1.StartInfo = p;
proc1.Start();
string result = "";
using (System.IO.StreamReader output = proc1.StandardOutput)
{
result = output.ReadToEnd();
}
string error = "";
using (System.IO.StreamReader output = proc1.StandardError)
{
error = output.ReadToEnd();
}
log.InfoFormat("SFTP result: {0}", result);
log.InfoFormat("{0}", error);
I am capturing the redirected stdout and stderr using streamreader. Now i can see the script upload.sh being run successfully and uploading the file to the remote server as well.
I took help from here:
How to capture Shell command output in C#?

Executing pdftk.exe with arguments in process

Currently struggling to get this process working:
const string pdfkPath = "pdftk.exe";
var paths = new List<string>();
paths.Add(#"C:\test.pdf");
paths.Add(#"C:\testje.pdf");
var cmd = String.Join(" ", paths) + " cat output " + #"C:\lel.pdf";
Process p = new Process();
p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
p.StartInfo.FileName = pdfkPath;
p.StartInfo.Arguments = cmd;
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();
Executing the exe file with the arguments using command line works, so what am I doing wrong here?
Thanks!
Found it ourselves! The problem was the output being directly on the C:\, folder between fixed it

Programmatically disable Password Complexity in Windows

I have spent all day looking for an answer but without luck.
I need to be able to disable the Password Complexity in the Local Security Policy on a stand-alone Windows 7 PC.
I have tried scripting with secedit.exe.
I have also messed a bit around with C#.
The end result shall be a script/program which will disable the policy and then create a new user account locally.
After some extended research I found out how to do it.
Posting the code here in case someone else needs to use it.
string tempFile = Path.GetTempFileName();
Process p = new Process();
p.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\secedit.exe");
p.StartInfo.Arguments = String.Format("/export /cfg \"{0}\" /quiet", tempFile);
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();
StringBuilder newCfg = new StringBuilder();
string[] cfg = File.ReadAllLines(tempFile);
foreach (string line in cfg)
{
if (line.Contains("PasswordComplexity"))
{
newCfg.AppendLine(line.Replace("1", "0"));
continue;
}
newCfg.AppendLine(line);
}
File.WriteAllText(tempFile, newCfg.ToString());
Process p2 = new Process();
p2.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\secedit.exe");
p2.StartInfo.Arguments = String.Format("/configure /db secedit.sdb /cfg \"{0}\" /quiet", tempFile);
p2.StartInfo.CreateNoWindow = true;
p2.StartInfo.UseShellExecute = false;
p2.Start();
p2.WaitForExit();

running bat file through c#.net code reg

I have run the bat file through dotnet in c# is as below
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "d://s.bat";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
it works fine while running through dotnet ide.
But my problem is when ever i run the above code after publishing through IIS it returns me error as
StandardOut-has-not-been-redirected-or-the-process-hasn-t-started-yet.
can you give me some guide lines to solve this problem?
Do this way, to overcome the error:-
StringBuilder content = new StringBuilder();
while ( ! p.HasExited ) {
content.Append(p.StandardOutput.ReadToEnd());
}
string output = content.ToString();
You have to use the RedirectStandardOutput = true.
Link from MSDN
Quote from link:
ProcessStartInfo.RedirectStandardOutput Property
Gets or sets a value that indicates whether the output of an application is written to the Process.StandardOutput stream.
A snippet from my issue to the same problem, when i was making sure our server was starting.
if (IsProcessRunning(ServerProcessName)) { return; }
var p = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = path,
RedirectStandardOutput = true,
UseShellExecute = false
}
};
p.Start();
var a = "";
while (!a.Contains("ServicesStarted"))
{
a = p.StandardOutput.ReadLine();
}

Categories

Resources