【问题标题】:How to create and delete NamedPipeServerStream in Powershell?如何在 Powershell 中创建和删除 NamedPipeServerStream?
【发布时间】:2022-07-19 23:24:46
【问题描述】:

我遇到了这样一种情况:一个进程以管理员身份运行,另一个进程以非管理员用户身份运行。第一个管理进程应该打开一个 pipeStream 以允许其他进程发送一些消息信息。

这里我遇到了多个问题:

  1. 我必须为 pipeStream 设置权限,允许客户端将一些数据写入此管道,即使用户不同,甚至没有管理员也是如此
  2. 管理进程应通过“WaitForConnectionAsync”等待连接
  3. 应该正确关闭 pipeStream 以允许再次运行相同的代码。

请看下面我的解决方案。

【问题讨论】:

    标签: powershell asynchronous named-pipes namedpipeserverstream


    【解决方案1】:

    这是我创建 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 {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.'
    

    这里是向其他进程发送消息的客户端代码:

     # 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.'
    

    我希望这个 code-sn-ps 可以帮助其他有类似用例的人,并解释一些使用 NamedPipeServerStream 的细节。

    【讨论】:

      猜你喜欢
      • 2013-08-09
      • 2015-06-28
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多