2017-04-25 143 views
0

我试图将在Linux中编写的powershell脚本传输到托管在Azure中的Windows计算机。这个想法是将脚本复制到Windows机器并执行它。我正在使用PyWinRM来完成这项任务。 PyWinRM没有直接的机制可以一次性传输文件。我们将不得不将文件转换为流,并对该文件进行一些字符编码,以便在传输之前与PowerShell内联。详细解释请参考click here。从Linux的流媒体文件到Windows python脚本去如下使用PyWinRM从Linux向Windows传输powershell脚本

winclient.py

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) 

现在,当我运行该脚本什么我得到的输出是

$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 |选择-ExpandProperty IPV4Address

有在上述各行密切关注,并与script_text字符串中的代码比较,你会发现变量的名称,如$主机,$ IPV4开始$关键在转移到窗口完成后丢失。 有人可以解释发生了什么事以及如何解决它? 在此先感谢。 :-)

+0

不一定是问题的答案,但您是否尝试过在Linux上运行PowerShell? https://github.com/PowerShell/PowerShell – lit

+0

这种情况是在Windows机器上执行任务..这里的兴趣是与windows-linux通信,而不是与powershell ..反正这是一个很好的信息,我会尝试它肯定.. –

回答

3

用单引号而不是双引号使用这里的字符串。这里的字符串也是将$var替换为其值的主题。

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

也就是说,您的Python部分可能没问题,但是在Powershell中执行的内容需要稍微修改。

+0

工作.. !!!非常感谢你......你真棒! –

相关问题