我需要能够在远程设备上创建进程,并使用PowerShell脚本向其发送命令。我需要这样做,因为我在使用命令时会收到提示。我一直试图通过使用Google搜索和以下链接找出如何执行此操作:http://tartarus.org/~simon/putty-snapshots/htmldoc/Chapter7.html#plink。通过该链接,我意识到在Plink中使用带有命令列表的文件由于以下原因而无法工作(从该链接复制并粘贴):
您可以在服务器上运行的任何非交互式命令 在命令行中,您可以使用Plink以批处理文件的形式运行。
它说"非交互式命令",这就是我正在使用的。我还尝试过使用带有命令列表的文件,但它并没有解决我的问题,因为我基本上需要给出一个命令,等待,然后在它提示我时给另一个命令。这是我在PuTTY FAQ中找到的,基本上我想尝试的内容:
可能你最好的选择是使用命令行连接Plink 工具。如果你可以启动Plink作为第二个Windows进程,并安排 为了让您的主要流程能够将数据发送到Plink流程, 并通过管道从它接收数据,然后你应该能够 从您的程序建立SSH连接。例如,这就是Windows的CVS。
编辑:根据user2460798的回答,我尝试了以下解决方案。我希望使用PuTTY并能够以这种方式发送命令。我现在的问题是我不知道如何向打开的PuTTY会话发送命令。所以基本上这段代码打开了一个PuTTY会话并尝试编写" ls"命令它,但没有任何反应。我不知道" ls"文字正在进行中。
$procInfo = New-Object Diagnostics.ProcessStartInfo
$procInfo.RedirectStandardOutput=$true
$procInfo.RedirectStandardInput=$true
$procInfo.RedirectStandardError=$true
$procInfo.FileName="putty.exe"
$procInfo.Arguments="-ssh -pw <password> <username>@<device>"
$procInfo.UseShellExecute=$false
$p=[diagnostics.process]::start($procInfo)
sleep -Milliseconds 3000
$p.StandardInput.WriteLine("ls")
答案 0 :(得分:2)
不确定理解您的问题,但这是我使用plink的方式
function plink
{
[CmdletBinding()]
PARAM
(
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[string] $remoteHost,
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[string] $login,
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[string] $passwd,
[Parameter(Mandatory=$True)]
[ValidateNotNullOrEmpty()]
[string] $command)
& c:\Tools\plink.exe -ssh $remoteHost -l $login -pw $passwd $command
return
}
$remoteHost = "192.168.1.1"
$login = "TheUserWhoCan"
$command1 = "/opt/compiere/apache-tomcat-6.0.32/bin/shutdown.sh "
$command2 = "cd /opt/compiere/apache-tomcat-6.0.32/bin && ./startWS.sh"
$command3 = "ps -edalf | grep java"
$passwd = Read-Host "Enter Password for $login"
write-host "Stopping tomcat" -ForegroundColor DarkGreen
plink -remoteHost $remoteHost -login compiere -command $command1 -passwd $passwd
Start-Sleep 10
write-host "Starting tomcat" -ForegroundColor DarkGreen
plink -remoteHost $remoteHost -login compiere -command $command2 -passwd $passwd
write-host "Looking for java processes"-ForegroundColor DarkGreen
plink -remoteHost $remoteHost -login compiere -command $command3 -passwd $passwd
答案 1 :(得分:1)
我不清楚你是否真的想要一些非交互式的东西。句子“它说”非交互式命令“,这就是我正在使用的。”听起来你想要非互动。但是“我基本上需要发出一个命令,等待,然后在它提示我时给另一个命令”听起来是互动的。由于不清楚我会回答互动案例。
FAQ中的第二个引用(“可能是你的......”)可以使用此处给出的代码来实现:How to run interactive commands in another application window from powershell,但是用plink.exe替换cmd.exe并根据需要更改命令行参数对于plink。
但一定要阅读代码之前的文字。它提到了几个警告。