问题描述
我想知道是否可以在我通过 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,stderr = ssh.exec_command(cmd6)
stdin.write(cmd5 + '\n')
stdin.flush()
time.sleep(5)
lines = stdout.readlines()
print (stdout.readlines())
解决方法
在服务器上运行 powershell
并将脚本提供给它的输入。
只需将这两者结合在一起:
- How to evaluate PowerShell script inputed from stdin
- Pass input/variables to command/script over SSH using Python Paramiko
一个简单的(未经测试的)例子:
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)