java - 如何在Linux操作系统中从Java调用 "Powershell script file"

标签 java linux powershell

类别:-

======================

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/

相关文章:

linux - 测量时间 : differences among gettimeofday, TSC 和时钟滴答

powershell - 使用 Powershell 同步文件夹 - 新建和编辑的文件

java - 在 Java 中,类型变量的边界只能出现在类型变量声明中,对吗?

java - TableView:如何在角菜单中启用加速器?

java - 使用android登录网站

php - 使用 PHP 从基于 Linux 的文件服务器上传/检索文件

linux - VPATH 在 makefile 中不起作用

powershell - 在 Azure Devops 的计划中执行 exe

list - powershell列表列表:条目初始化由地址而不是值完成

java - 如何计算每个复选框中的所有真值和假值