powershell on linux docker image - c#

I'm using a linux docker image with powershell and few modules installed on it.
Programmatically, my code do not see the modules.
For verification, if I start the image and instanciate powershell, I can run commands and confirm that the modules are installed:
kubectl run -i --tty test --image=urlofimage:20211008.8 --command pwsh
However, my code do not see the modules.
The extract of code below works in a windows machine, but returns the following error in the docker image:
This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system.
internal const string NewSessionScript = "New-PSSession -ConfigurationName:Microsoft.Exchange -Authentication:Basic -ConnectionUri:{0} -Credential $cred -AllowRedirection";
this._runspace.SetCredential(userName, password);
var command = new PSCommand();
command.AddScript(string.Format(NewSessionScript, connectionUri));
var result = this._runspace.ExecuteCommand<PSSession>(command);
Question:
It looks like the code is instanciating powershell "in memory" but does not use the powershell that is installed on the machine.
How can I use it and leverage an image with all my powershell dependancies installed?

Related

Running .NET framework console-app service on Docker

I'm trying to get a service on-boarded to Docker containers.
Target Framework - .NET Framework 4.6.1
Output type - Console Application
When I initially tried to right click -> Add -> Docker Support on the project in the Visual Studio 2017 sln I got a prompt "You cannot add Docker support to this project type"
I went ahead and created a Dockerfile by hand and placed it in the root. This is what it looks like:
FROM microsoft/windowsservercore
SHELL ["powershell", "-command"]
RUN Add-WindowsFeature NET-Framework-45-ASPNET, Web-Asp-Net45
EXPOSE 80
EXPOSE 5000
EXPOSE 13134
ADD ./bin/Debug/net461/win7-x64 .
COPY ./bin/cert-that-needs-to-be-installed.pfx /cert-that-needs-to-be-installed.pfx
RUN $Secure_String_Pwd = ConvertTo-SecureString "thePasswordToTheCert!" -AsPlainText -Force; \
Import-PfxCertificate -FilePath .\cert-that-needs-to-be-installed.pfx -CertStoreLocation Cert:\LocalMachine\My -Exportable -Password $Secure_String_Pwd;
ENV ASPNETCORE_ENVIRONMENT="Development"
ENTRYPOINT ["./ServiceName.exe"]
Upon doing the following, I was able to successfully create an image and also a container with the service running on it: (the prod version listens on port 5000 while the test one listens on 13134 and those ports are also open in my localhost Firewall)
docker build -t ServiceName .; docker run -p 5000:5000 -p 13134:13134 -it ServiceName
I am able to get the ip of the container by doing this:
docker inspect <containerId>
Now when I try to test the service by doing a HttpGet call to an API using Postman I don't get a response. I have the docker container open in my cmd prompt and I don't see my request coming in either.
My service works fine on a Windows VM.
Since my GET calls don't even seem to reach the container I fear I am doing the port mapping wrong/or is it something else?
From what I know you don't need the ip of the container, the ports have been projected on your localhost, you should get a response when you make REST calls to localhost:5000/localhost:13134

Mono TLS1.2 issues - btls-cert-sync "command not found"

Summary:
My company uses TargetProcess (TP) to track progress on open projects and we've created a relatively small bit of code that imports updates to TargetProcess.
Currently upon build submission, we spin up a debian docker image, with Mono pre-installed, and it runs our small .NET(C#) program to connect our updates to TP.
Repro:
It appears TP recently updated their API to only accept TLS1.2 connections, so we had to create a new docker image with Mono 4.8, the Alpha channel, on it (per this article).
The program still doesn't work out of the box with this new Mono installation on a docker image so we took a few steps: (following the prompting from Mono's Security FAQ)
// Made sure that the most current version ca-certificates-mono is installed
// and it seems to have been installed upon installation of mono 4.8
apt-get install ca-certificates-mono
// This should be an unnecessary step from what I read, but ran anyway
cert-sync /etc/ssl/certs/ca-certificates.crt
// lastly btls-cert-sync command, but can't seem to get it to not return
// "command not found" no matter wher I try running it
btls-cert-sync
Testing:
There seems to be a really helpful thread on how to test if your certs are formatted correctly. After running this test command in my docker image, I'm still seeing the failure message below.
MONO_TLS_PROVIDER=btls csharp -e 'Console.WriteLine (new System.Net.WebClient ().DownloadString ("https://www.howsmyssl.com/").IndexOf ("1.2"))'
// error message
System.Net.WebException: Error: TrustFailure (Ssl error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED) ---> Mono.Btls.MonoBtlsException: Ssl error:1000007d:SSLroutines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED
Any help or advice to get our instance of mono to accept TLS1.2 connections would be awesome.
btls-cert-sync is a shell script for btls-cert-sync.exe
Find btls-cert-sync.exe, normally installed in 4.8.0/lib/mono/4.8 and run it with mono:
mono btls-cert-sync.exe
As of mono 4.8 beta 3, btls-cert-sync seems to have been merged into cert-sync.
Do make sure that you have an up-to-date version of cert-sync as it is possible to get old versions of cert-sync still installed even if you have updated mono because the ca-certificates-mono package has not been updated (Linux).
If you look at the cert-sync output you will see
Mono Certificate Store Sync - version 4.8.0.0
...
Importing into legacy system store:
...
Importing into BTLS system store:
...

Error while Trying to load Powershell Module "MSOnline" in ASP.NET web app

Good morning I have one problem trying o load a Powershell Module called MSOnline in a ASP.NET
After following this links:
http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/
http://blogs.technet.com/b/educloud/archive/2013/01/23/managing-office-365-for-education-using-powershell.aspx
This is a Button that run a script via Code Behind in C#. When I was trying to load the module it threw an exception.
protected void Bexecute_Click(object sender, EventArgs e)
{
// Import-Module MSOnline
try
{
//Loading MSOnline using a InitialSessionState
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[] { "MSOnline" });
//Before the solution iss has an exception of "not found" the MSOnline Module
//Create a runspace
Runspace test = RunspaceFactory.CreateRunspace(iss);
//Open a Runspace
test.Open();
//Create a Pipeline
Pipeline pipeLine = test.CreatePipeline();
//Create the StringBuilder to get append the script
StringBuilder script = new StringBuilder();
//Take the script from Tscript (TextBoxt with ID="Tscript" in default.aspx
script.AppendLine(#"Get-Module -ListAvailable");
//Add the script and commands to the pipeline;
pipeLine.Commands.AddScript(script.ToString());
//Execute script and get the PSObject Results collection
Collection<PSObject> resultObjects = pipeLine.Invoke();
//Close the Runspace
test.Close();
if (resultObjects.Count > 0)
{
/*** DO SOMETHING WITH THE PSObjects ***/
}
}
catch (System.Management.Automation.RuntimeException ex)
{
status.AppendLine(ex.Message);
}
}
What I need is what could be wrong. I referenced the system.management.automation (dll). But I don't have a clue why is not listed if it's installed it. Thank you for the help.
I have found MSOnline .dll files in : C:\windows\system32\WindowsPowerShell\v1.0\Modules\MSOnline
But If I tried to add manually from visual studio it says "that MSOnline doesn't exist".
This is quite weird, because all have same permissions to folder. What's going on! :S This is so frustrating...
To get ASP.NET web app run under x64 bit architecture you should do this:
1, MS Online Services Assistant needs to be downloaded and installed
Microsoft Online Services Sign-In Assistant – 64 bit version http://go.microsoft.com/fwlink/?linkid=236300
2.MS Online Module for PowerShell needs to be downloaded and installed
Microsoft Online Services Module for Windows PowerShell (64-bit version) http://go.microsoft.com/fwlink/?linkid=236297
After this step you can run: get-module -ListAvailable and the Module MSOnline will be listed.
But it is still not working on 64 bits SOs. the original poster used win8 64bits and I am using win 8.1 64 bits and it works as well.
Copy the MSOnline module folder from (Path1) to (Path2) where
(Path1) -> "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\MSOnline" and
(Path2) -> "C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\MSOnline"
Considering I'm running this on VS2013 under Windows 8.1 and 64 bits arquitecture.
After doing this the MSOnline Module is listed in the Get-Module -ListAvailable (from webapp, not just for powershell)), so I could import it and use it.

.ps1 cannot be loaded because the execution of scripts is disabled on this system

I run this code to execute PowerShell code from an ASP.NET application:
System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
runspace.Open();
System.Management.Automation.Runspaces.Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(#"\\servername\path");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
But I am getting an error:
.ps1 cannot be loaded because the execution of scripts is disabled on
this system. Please see "get-help about_signing" for more details.
The same code runs fine from a command prompt or a windows (Windows Forms) application.
Your script is blocked from executing due to the execution policy.
You need to run PowerShell as administrator and set it on the client PC to Unrestricted. You can do that by calling Invoke with:
Set-ExecutionPolicy Unrestricted
There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.
Look in your Windows directory for System32 and SysWOW64.
Repeat these steps for each directory:
Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
Check the current setting for ExecutionPolicy:
Get-ExecutionPolicy -List
Set the ExecutionPolicy for the level and scope you want, for example:
Set-ExecutionPolicy -Scope LocalMachine Unrestricted
Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.
The problem is that the execution policy is set on a per user basis. You'll need to run the following command in your application every time you run it to enable it to work:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned
There probably is a way to set this for the ASP.NET user as well, but this way means that you're not opening up your whole system, just your application.
(Source)
You need to run Set-ExecutionPolicy:
Set-ExecutionPolicy Unrestricted <-- Will allow unsigned PowerShell scripts to run.
Set-ExecutionPolicy Restricted <-- Will not allow unsigned PowerShell scripts to run.
Set-ExecutionPolicy RemoteSigned <-- Will allow only remotely signed PowerShell scripts to run.
I had a similar issue and noted that the default cmd on Windows Server 2012 was running the x64 one.
For Windows 7, Windows 8, Windows Server 2008 R2 or Windows Server 2012, run the following commands as Administrator:
x86
Open C:\Windows\SysWOW64\cmd.exe
Run the command: powershell Set-ExecutionPolicy RemoteSigned
x64
Open C:\Windows\system32\cmd.exe
Run the command powershell Set-ExecutionPolicy RemoteSigned
You can check mode using
In CMD: echo %PROCESSOR_ARCHITECTURE%
In Powershell: [Environment]::Is64BitProcess
I hope this helps you.
Try This:
Set-ExecutionPolicy -scope CurrentUser Unrestricted
If you faced this error while running json-server and landed here on this page.
one alternate solution is to run it using npx directly without installing it.
npx json-server --watch db.json

Hadoop streaming with C# and Mono : IdentityMapper being used incorrectly

I have mapper and reducer executables written in C#.
I want to use these with Hadoop streaming.
This is the command I'm using to create the Hadoop job...
hadoop jar $HADOOP_HOME/contrib/streaming/hadoop-streaming-*.jar
-input "/user/hduser/ss_waits"
-output "/user/hduser/ss_waits-output"
–mapper "mono mapper.exe"
–reducer "mono reducer.exe"
-file "mapper.exe"
-file "reducer.exe"
This is the error encountered by each mapper...
java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, recieved org.apache.hadoop.io.LongWritable
at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.collect(MapTask.java:1014)
at org.apache.hadoop.mapred.MapTask$OldOutputCollector.collect(MapTask.java:592)
at org.apache.hadoop.mapred.lib.IdentityMapper.map(IdentityMapper.java:38)
at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:50)
at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:436)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:372)
at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
Based on the call-stack, the problem seems to be that the (Java) IdentityMapper class is being used as the mapper. (Which explains why the type mismatch error was caused). The mapper should have been the executable "mono mapper.exe".
Any ideas why mono mapper.exe is not being used?
The mapper.exe and reducer.exe have the following permissions: -rwxr-xr-x
I am able to successfully execute mono mapper.exe from the unix command shell and have it read in text from stdin and write to stdout.
Environment:
Ubuntu Server 12.04 LTS (VM running on Azure)
Hadoop 1.0.4
Mono 2.10
Assuming mono is in the PATH, do you need the full path to mapper.exe and reducer.exe? i.e.
hadoop jar $HADOOP_HOME/contrib/streaming/hadoop-streaming-*.jar
-input "/user/hduser/ss_waits"
-output "/user/hduser/ss_waits-output"
–mapper "mono /path/to/mapper.exe"
–reducer "mono /path/to/reducer.exe"
-file "mapper.exe"
-file "reducer.exe"

Categories