我正在尝试将用Linux编写的powershell脚本传输到Azure托管的Windows机器上。这样做的目的是将脚本复制到windows机器并执行它。我正在使用PyWinRM来完成这个任务。在PyWinRM中没有直接机制可以一次传输文件。我们必须将文件转换为流,并对文件执行一些字符编码,以便在传输前与PowerShell内联。有关详细解释,单击此处。用于将文件从Linux流到windows的python脚本如下所示
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\ IPV4Address
仔细查看上面的行,并将其与代码中的script_text字符串进行比较,您将发现在完成对windows的传输之后,会发现诸如$hostname、以$键开头的$ipV4等变量名缺失。有人能解释一下发生了什么事以及如何解决吗?提前谢谢。:-)
发布于 2017-04-25 13:56:08
使用这里-字符串与单撇号,而不是双引号。这里-字符串也是将$var替换到其值中的主题。
$s = @'
$hostname='www.google.com'
$ipV4 = Test-Connection -ComputerName $hostname -Count 1 | Select -ExpandProperty IPV4Address
'@ | %{ $_.Replace("`n","`r`n") }也就是说,Python部分可能很好,但是在Powershell中执行的内容需要稍加修改。
https://stackoverflow.com/questions/43612432
复制相似问题