首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用PyWinRM将powershell脚本从Linux传输到Windows

用PyWinRM将powershell脚本从Linux传输到Windows
EN

Stack Overflow用户
提问于 2017-04-25 13:44:13
回答 1查看 1.7K关注 0票数 0

我正在尝试将用Linux编写的powershell脚本传输到Azure托管的Windows机器上。这样做的目的是将脚本复制到windows机器并执行它。我正在使用PyWinRM来完成这个任务。在PyWinRM中没有直接机制可以一次传输文件。我们必须将文件转换为流,并对文件执行一些字符编码,以便在传输前与PowerShell内联。有关详细解释,单击此处。用于将文件从Linux流到windows的python脚本如下所示

winclient.py

代码语言:javascript
复制
script_text  = """$hostname='www.google.com'
$ipV4 = Test-Connection -ComputerName $hostname -Count 1  | Select  -ExpandProperty IPV4Address
"""

part_1 = """$stream = [System.IO.StreamWriter] "gethostip.txt"
    $s = @"
    """
    part_2 = """
    "@ | %{ $_.Replace("`n","`r`n") }
    $stream.WriteLine($s)
    $stream.close()"""

    reconstructedScript = part_1 + script_text + part_2
    #print reconstructedScript
    encoded_script = base64.b64encode(reconstructedScript.encode("utf_16_le"))

    print base64.b64decode(encoded_script)
    print "--------------------------------------------------------------------"
    command_id = conn.run_command(shell_id, "type gethostip.txt")
    stdout, stderr, return_code = conn.get_command_output(shell_id, command_id)
    conn.cleanup_command(shell_id, command_id)
    print "STDOUT: %s" % (stdout)
    print "STDERR: %s" % (stderr)

现在,当我运行脚本时,我得到的输出是

代码语言:javascript
复制
    $stream = [System.IO.StreamWriter] "gethostip.ps1"
    $s = @"
    $hostname='www.google.com'
    $ipV4 = Test-Connection -ComputerName $hostname -Count 1  | Select -ExpandProperty IPV4Address
    "@ | %{ $_.Replace("`n","`r`n") }
    $stream.WriteLine($s)
    $stream.close()
   --------------------------------------------------------------------
   STDOUT: ='www.google.com'
   = Test-Connection -ComputerName  -Count 1  | Select -ExpandProperty IPV4Address


    STDERR: 
    STDOUT: 
    STDERR:

这里的争用点是输出中的下列行。

STDOUT:='www.google.com‘= Test-Connection -ComputerName -Count 1\ IPV4Address

仔细查看上面的行,并将其与代码中的script_text字符串进行比较,您将发现在完成对windows的传输之后,会发现诸如$hostname、以$键开头的$ipV4等变量名缺失。有人能解释一下发生了什么事以及如何解决吗?提前谢谢。:-)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-25 13:56:08

使用这里-字符串与单撇号,而不是双引号。这里-字符串也是将$var替换到其值中的主题。

代码语言:javascript
复制
$s = @'
$hostname='www.google.com'
$ipV4 = Test-Connection -ComputerName $hostname -Count 1  | Select -ExpandProperty IPV4Address
'@ | %{ $_.Replace("`n","`r`n") }

也就是说,Python部分可能很好,但是在Powershell中执行的内容需要稍加修改。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43612432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档