2017-04-25 20 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

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

相關問題