【问题标题】:Running local PowerShell script on remote SSH server在远程 SSH 服务器上运行本地 PowerShell 脚本
【发布时间】:2021-04-26 14:19:37
【问题描述】:

我想知道是否可以在我通过 SSH 连接的远程服务器上运行本地 PowerShell 脚本。这最好通过像 Paramiko 这样的脚本来完成,我可以在其中运行 Paramiko Python 脚本,它可以完成所有工作——SSH 并同时运行本地 PowerShell 脚本。

我四处搜索,似乎没有任何确凿的答案。

我已经尝试过 Python Paramiko,它确实有效。但是,我所能做的就是通过 SSH 连接到远程服务器并使用 SFTP 复制 PowerShell 脚本文件来运行脚本。是否可以根本不使用 SFTP? 哪里可以在本地运行脚本而不发送它?

谢谢。

我尝试过的代码:

cmd4 = "powershell; echo './script.ps1' | powershell -File C:\\Users\\Desktop\\script.ps1"
cmd5 = "C:\\Users\\Desktop\\script.ps1"
stdin, stdout, stderr = ssh.exec_command(cmd4)
stdin.write(cmd5 + '\n')
stdin.flush()
time.sleep(5)

lines = stdout.readlines()
print (stdout.readlines())

我尝试打印stdout,但它是空的。

也试过这个:

cmd5 = "C:\\Users\\Desktop\\script.ps1"
cmd6 = "powershell; echo './script.ps1;' | powershell -noprofile -noninteractive -command { $input | iex }"
stdin, stdout, stderr = ssh.exec_command(cmd6)
stdin.write(cmd5 + '\n')
stdin.flush()
time.sleep(5)

lines = stdout.readlines()
print (stdout.readlines())

【问题讨论】:

    标签: powershell ssh paramiko fabric plink


    【解决方案1】:

    在服务器上运行 powershell 并将脚本提供给它的输入。

    只需将这两者结合起来:

    一个简单的(未经测试的)示例:

    with open("C:\\Users\\Desktop\\script.ps1", "r") as f:
        script = f.read() + "\n"
    
    cmd = "powershell -noprofile -noninteractive -"
    stdin, stdout, stderr = ssh.exec_command(cmd)
    stdout.channel.set_combine_stderr(True)
    stdin.write(script)
    stdin.flush()
    stdin.close()
    
    lines = stdout.readlines()
    print(lines)
    

    【讨论】:

      猜你喜欢
      • 2013-12-28
      • 2010-11-03
      • 1970-01-01
      • 2019-12-20
      • 2018-03-14
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多