类别:-
======================
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestPowershell {
public static void main(String[] args) throws IOException
{
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("cmd powershell \"\\Test\\Powershell\\powershell.ps1\" ");
proc.getOutputStream().close();
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
proc.getOutputStream().close();
}
}
我试图在linux环境中使用java执行powershell文件,我遇到了异常(上面我附加了类和异常),请为我提供一个可以在linux中执行powershell脚本文件的测试类。提前致谢
最佳答案
第一次下载 FreeSSHD http://www.freesshd.com/?ctt=download在你的Windows(服务器)中。确保以管理员身份运行它。
要设置 FreeSSHD,请遵循此 URL http://www.techrepublic.com/blog/tr-dojo/set-up-a-free-ssh-server-on-windows-7-with-freesshd/设置完成后,您可以从 linux 或使用 putty ssh 该 Windows 系统。
使用java从Linux到远程Windows系统执行powershell脚本
package com.sysvana.router.config;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class Test {
static String hostname = "10.1.10.60";
static String username = "administrator";
static String password = "P@ssw0rd";
public static void main(String[] args) throws IOException {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword (username, password);
if (isAuthenticated == false){
System.out.println("authentication failed");
}
System.out.println(isAuthenticated);
Session sess = conn.openSession ();
sess.execCommand ("powershell C:/Users/Administrator/Desktop/test.ps1");
InputStream stdout = new StreamGobbler (sess.getStdout ());
BufferedReader br = new BufferedReader (new InputStreamReader (stdout));
while (true)
{
String line = br.readLine ();
if (line == null) break;
System.out.println (line);
}
System.out.println ("Exit code" + sess.getExitStatus ());
sess.close ();
conn.close ();
}
}
使用 Ganymed SSH-2 jar http://www.ganymed.ethz.ch/ssh2/
关于java - 如何在Linux操作系统中从Java调用 "Powershell script file",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53886281/