i want to execute OS Command both windows and docker container (linux). When i control on windows every command which i entered work well because i can see output. When i build Dockerfile and run my app with container, send a few command i didn't take output what i expected.
My function is bellow.
public string RunCommand(string arguments)
{
var argsPrepend = "-c ";
var shellName = "/bin/sh";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
shellName = @"C:\Windows\System32\cmd.exe";
argsPrepend = "/c ";
}
try
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = shellName,
Arguments = argsPrepend arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
}
};
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return output;
}
catch (Exception ex)
{
return ex.ToString();
}
}
When i send pwd and ls command it works well.
When i want to execute "ls -la /" or "cat /etc/passwd" i didn't get right output.
swagger-ls-la swagger-cat-etc-passwd
How can i execute OS Command over Docker Container ? What's the problem which i make or i face ?
CodePudding user response:
1 - If you can access the directories you are running your file in and not other root directories, then there is the problem of not being able to read the file. You may need to check if the user you are running the file from has access.
2 - You may need to take a look at the "SecurityContext" configurations. I don't know about container structures. Maybe it's hardening in itself as a precaution. You may need to give permission yourself.
Best Regards.
CodePudding user response:
Thanks for your helping. After gave my all 2 days's time :) i solved at the end. After i changed function likes bellow, everything works well.
public string RunCommand(string arguments)
{
var shellName = "/bin/bash";
var argsPrepend = "-c ";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
shellName = @"C:\Windows\System32\cmd.exe";
argsPrepend = "/c ";
}
try
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = shellName,
Arguments = argsPrepend "\"" arguments "\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
}
};
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return output;
}
catch (Exception ex)
{
return ex.ToString();
}
}