简体   繁体   English

如何在 Powershell 中创建和删除 NamedPipeServerStream?

[英]How to create and delete NamedPipeServerStream in Powershell?

I was struggling with a scenario where I had one process running as admin and another process running as non-admin user.我在一个场景中苦苦挣扎,其中一个进程以管理员身份运行,另一个进程以非管理员用户身份运行。 The first admin-process should open a pipeStream to allow the other process sending some message information.第一个管理进程应该打开一个 pipeStream 以允许其他进程发送一些消息信息。

Here I had multiple problems:在这里我遇到了多个问题:

  1. I had to set the permission for the pipeStream allowing the client to write some data into this pipe even if the user is not the same and even no admin我必须为 pipeStream 设置权限,允许客户端将一些数据写入此管道,即使用户不同,甚至没有管理员
  2. The admin process should wait for the connection via 'WaitForConnectionAsync'管理进程应通过“WaitForConnectionAsync”等待连接
  3. The pipeStream should be properly closed to allow running the same code again. pipeStream 应该正确关闭以允许再次运行相同的代码。

See below my solution.请参阅下面我的解决方案。

Here is my server-side code that creates the pipeStream:这是我创建 pipeStream 的服务器端代码:

# server process running as admin and waiting for client response:

cls
$ps  = [System.IO.Pipes.PipeSecurity]::new()
$all = [System.Security.Principal.WellKnownSidType]::WorldSid
$sid = [System.Security.Principal.SecurityIdentifier]::new($all,$null)
$ar  = [System.IO.Pipes.PipeAccessRule]::new($sid, 'ReadWrite', 'Allow')
$ps.SetAccessRule($ar)

$async = [System.IO.Pipes.PipeOptions]::Asynchronous
$pipe  = [System.IO.Pipes.NamedPipeServerStream]::new('test123','In',1,0,$async,512,512,$ps)

$timeout = [timespan]::FromSeconds(10)
$source = [System.Threading.CancellationTokenSource]::new($timeout)
$conn = $pipe.WaitForConnectionAsync($source.token)
do {
    # some other stuff here while waiting for connection
    sleep -Seconds 1
} until ($conn.IsCompleted)

$data = $null
if ($pipe.IsConnected) {
    $sr = [System.IO.StreamReader]::new($pipe)
    $data = $sr.ReadLine()
    $sr.Dispose()
}
$pipe.Dispose()
write-host "response: $data"
'end.'

and here the client-side code to send a message to the other process:这里是客户端代码向另一个进程发送消息:

 # client process running as non-admin user sending a response:

cls
$pipe = [System.IO.Pipes.NamedPipeClientStream]::new('.','test123','Out')
try {$pipe.Connect(10000)} catch {}
if ($pipe.IsConnected) {
    $sw = [System.IO.StreamWriter]::new($pipe)
    $sw.WriteLine('hello world!')
    $sw.Flush()
    $sw.Dispose()
}
'end.'

I hope this code-snippets will help others with a similar use case and also explains a little bit some details working with a NamedPipeServerStream.我希望这段代码片段能帮助其他有类似用例的人,并解释一些使用 NamedPipeServerStream 的细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM