I've got this project that needs to get finished in two days and I'm nearly done with it. Except there's a part of it that needs to start another app and run it as a different domain user.
So far I've got this in code:
Process proc = new Process();
System.Security.SecureString ssPwd = new System.Security.SecureString();
string password = "SomePassword";
for (int x = 0; x < password.Length; x++)
{
ssPwd.AppendChar(password[x]);
}
ProcessStartInfo StartInfo = new ProcessStartInfo
{
FileName = "Translink.exe",
WorkingDirectory = #"C:\Program Files\Western Union\Universal-Release",
UserName = "someuser",
Domain = "somedomain",
Password = ssPwd,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
proc = Process.Start(StartInfo);
proc.WaitForExit();
So when I make a call with and without user and password for example:
C:\Windows\System32\notepad.exe
it runs in both cases but everytime I try to run that particular app "Translink.exe" from either Program Files or Program Files (x86) it just won't run at all with or without runas.
And I've ran out of things to try, I think I've tried everything so far in stackoverflow as there were other similar articles but I think I must be going wrong somewhere specifically.
Related
I am basically trying to create and run a Windows Service on a server. This service has mainly 2 jobs,
To log a timestamp to a file on a UNC (different Server path) so as to check access
Call a simple console app using a different user
Now, I have created the windows service, but it won't log in the Server path as it is started via Local system. So I tried to deploy it using a user account with access to the Server Path and it logged, but then the whole point is to us the local system.
So now, i changed the requirement a little bit, Now is it possible to deploy the service as Local System only , but instead of directly logging on the server path, i would rather make the console app do the logging. But how should I make the console app run as a different user account.
This is the code I am using for calling the console app via a different user (mind you the service is run under LocalSystem), and it is either giving the error, "Cannot find the file specified" or "Invalid Directory Name" but i assure you both the things exist. I even used the paths fed in the startInfo by debugging to check.
public static void InitiateCommandProcess()
{
Process process = new Process();
SecureString ssPwd = new SecureString();
string fileName = ConfigurationManager.AppSettings["FileName"];
string workingDirectory = ConfigurationManager.AppSettings["ApplicationDirectory"];
string param = ConfigurationManager.AppSettings["PARAM"];
string userName = "myUserName";
string password = "MyPassWord";
for (int x = 0; x < password.Length; x++)
{
ssPwd.AppendChar(password[x]);
}
ProcessStartInfo startInfo = new ProcessStartInfo
{
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
ErrorDialog = false,
FileName = #"" + fileName,
WorkingDirectory = #"" + workingDirectory,
Arguments = #"" + param,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
Domain = "EMEA",
UserName = userName,
Password = ssPwd
};
process.StartInfo = startInfo;
try
{
Logger.Log($"Working in Directory Path : {workingDirectory} );");
Logger.Log($" Username : {userName} and Executing : {fileName}");
process.Start();
Logger.Log($"Process \"{ConfigurationManager.AppSettings["FileName"]}\" Executed at {DateTime.Now}");
}
catch (Exception ex)
{
Logger.Log($"Error occured in command process execution, Message : {ex.Message}", true);
}
}
The server path is like this, "\dfs\folder\folder..."
I am a little new to this so please bear with me.
I'm trying to write a C# console application that will launch runas.exe through cmd then run another application as that user. I've taken one of the suggestions listed below (and added a little bit) as it seems the most promising.
Process cmd = new Process();
ProcessStartInfo startinfo = new ProcessStartInfo("cmd.exe", #"/K C:\Windows\System32\runas.exe /noprofile /user:DOMAIN\USER'c:\windows\system32\notepad.exe\'")
{
RedirectStandardInput = true,
UseShellExecute = false
};
cmd.StartInfo = startinfo;
cmd.Start();
StreamWriter stdInputWriter = cmd.StandardInput;
stdInputWriter.Write("PASSWORD");
cmd.WaitForExit();
When I launch the application it asks for the password before the command itself causing there to be an error with runas.exe
I'm pretty sure UseShellExecute = false is causing the error but the StreamWriter doesn't work without it so I'm not sure what to do.
The /c argument runs comman line and terminates, so you could not see results (and it's a large C), see her : http://ss64.com/nt/cmd.html
Try to use "/K".
I did it with your command and i see results in another window.
ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/K ping PC -t");
Process.Start(startInfo);
Your process should have RedirectStandardInput = true
var p = new Process();
var startinfo = new ProcessStartInfo("cmd.exe", #"/C C:\temp\input.bat")
{
RedirectStandardInput = true,
UseShellExecute = false
};
p.StartInfo = startinfo;
p.Start();
StreamWriter stdInputWriter = p.StandardInput;
stdInputWriter.Write("y");
This program launches input.bat, and then sends the value y to it's standard input.
For completeness, input.bat example:
set /p input=text?:
echo %input%
I found a solution in the following post. I had to forgo most of the structure I was working with but I can now successfully run notepad as my desired user with the code listed below.
var pass = new SecureString();
pass.AppendChar('p');
pass.AppendChar('a');
pass.AppendChar('s');
pass.AppendChar('s');
pass.AppendChar('w');
pass.AppendChar('o');
pass.AppendChar('r');
pass.AppendChar('d');
var runFileAsUser = new ProcessStartInfo
{
FileName = "notepad",
UserName = "username",
Domain = "domain",
Password = pass,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process.Start(runFileAsUser);
I'm trying to execute a batch file that is located on a remote machine with the following line of code:
System.Diagnostics.Process.Start(\\10.0.24.103\somePath\batchFile.bat);
And it blocks on this line of code. When I try to run it manually (by writing that address in Windows Explorer), it works, but I have to accept a security warning message first. I'm assuming this is why it's blocking when it's done through code...is there any way to force it to execute through code?
I solved my problem by adding more detail to the ProcessStartInfo object:
var process = new Process();
var startInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "cmd.exe",
Arguments = "/c \"\"" + batchFile + "\"\"",
WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
process.StartInfo = startInfo;
process.Start();
process.WaitForExit(30000);
I needed to specify to use cmd.exe, as well as surrounding the batchFile path in double quotes in case there are spaces in the path.
Try prefacing it with cmd /c(that's a space after /c).
Is this IP address a Windows machine on your domain etc.
I'd like to use C# to execute a shell script.
Based on similar questions I came to a solution that looks like this.
System.Diagnostics.Process.Start("/Applications/Utilities/Terminal.app","sunflow/sunflow.sh");
It currently opens Terminal, then opens the shell file with the default application (Xcode in my case). Changing the default application is not an option, since this app will need to be installed for other users.
Ideally the solution will allow for arguments for the shell file.
I can't test with a Mac right now, but the following code works on Linux and should work on a Mac because Mono hews pretty closely to Microsoft's core .NET interfaces:
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = "foo/bar.sh",
Arguments = "arg1 arg2 arg3",
};
Process proc = new Process()
{
StartInfo = startInfo,
};
proc.Start();
A few notes about my environment:
I created a test directory specifically to double-check this code.
I created a file bar.sh in subdirectory foo, with the following code:
#!/bin/sh
for arg in $*
do
echo $arg
done
I wrapped a Main method around the C# code above in Test.cs, and compiled with dmcs Test.cs, and executed with mono Test.exe.
The final output is "arg1 arg2 arg3", with the three tokens separated by newlines
Thanks Adam, it is good starting point for me. However, for some reason when I tried with above code (changed to my needs) I am getting below error
System.ComponentModel.Win32Exception: Exec format error
see below code that gives above error
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = "/Users/devpc/mytest.sh",
Arguments = string.Format("{0} {1} {2} {3} {4}", "testarg1", "testarg2", "testarg3", "testarg3", "testarg4"),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
Process proc = new Process()
{
StartInfo = startInfo,
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string result = proc.StandardOutput.ReadLine();
//do something here
}
and spent some time and come up with below and it is working in my case - just in case if anyone encounter this error try below
Working Solution:
var command = "sh";
var scriptFile = "/Users/devpc/mytest.sh";//Path to shell script file
var arguments = string.Format("{0} {1} {2} {3} {4}", "testarg1", "testarg2", "testarg3", "testarg3", "testarg4");
var processInfo = new ProcessStartInfo()
{
FileName = command,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
Process process = Process.Start(processInfo); // Start that process.
while (!process.StandardOutput.EndOfStream)
{
string result = process.StandardOutput.ReadLine();
// do something here
}
process.WaitForExit();
In my .net web application, I need to launch another program as a new process - under a different user account (one with higher priviledges). My code runs without error, but I never get any output (I've tried Redirecting the output), and the program doesn't seem to execute at all. Its not an error with the User auth details, I've tried a bogus username and sure enough it throws a valid exception in that case. Nothing gets added to the event log.
SecureString passwordString = new SecureString();
foreach (char c in "MyPassword")
{
passwordString.AppendChar(c);
}
var process = new System.Diagnostics.Process
{
StartInfo =
{
UserName = "myuser", Password = passwordString, Domain = "MyDomain",
WorkingDirectory = HttpContext.Request.MapPath("~/bin"),
UseShellExecute = false,
FileName = HttpContext.Request.MapPath("~/bin") + "\\ServerCertificateImporter.exe",
Arguments = instanceLocationId.ToString(),
CreateNoWindow = true,
RedirectStandardInput = false,
RedirectStandardOutput = false,
RedirectStandardError = false
}
};
process.Start();
process.WaitForExit();
process.Close();
As Yahia pointed out, this was caused by the fact that I was trying to call a program with a different user account - and windows didn't want me to do that.