Java psexec交互式远程命令行

时间:2017-07-11 15:38:17

标签: java windows remote-access psexec

我与psexec有问题,因为它不是互动的。它在运行命令后立即返回以打开命令提示符

这是我的Connection类:

package testProject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;


public class ConTest {

    private ProcessBuilder process;
    private Process connection;
    private String main_connection;;

    public ConTest(String host, String user, String password) {
        process = new ProcessBuilder("cmd.exe");
        process.redirectErrorStream(true);
        main_connection="<path to psexec>\psexec.exe \\\\" + host + 
                " -accepteula -nobanner -u " + user + " -p " + password +" cmd";
    }

    public void runCommand(String command) throws Exception{

        /* Variable Declaration */
        String          readline;
        PrintStream     output;
        BufferedReader  input;

        /* Variable Initialization */
        connection = process.start();
        output = new PrintStream(connection.getOutputStream());
        input = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        /* Running the commands on the Host */

        output.println(main_connection);
        output.println(command);
        output.println("exit");
        output.close();

        /*print the output from the command*/
        while ((readline = input.readLine()) != null) {
            System.out.println(readline);
        }

        input.close();
        connection.waitFor();
    }
}

然后我使用以下

来调用它
package testProject;

public class mainClass {

    public mainClass() {
    }

    public static void main(String[] args) throws Exception {

        ConTest con = new ConTest(<IP>, <Admin>, <Password>);
        con.runCommand("ping localhost");

    }
}

输出显示它连接到主机,但在写入ping localhost命令之前它只是断开连接

这是输出

C:><path to psexec>\psexec.exe \\<IP> -accepteula -nobanner -u <Admin> -p <Password> cmd
Microsoft Windows [Version 6.1.7601]Connecting to <IP>...


Starting PSEXESVC service on <IP>...


Connecting with PsExec service on <IP>...


Starting cmd on <IP>...



cmd exited on <IP> with error code 0.

C:\>ping localhost

后面是ping stats

如何让命令提示符保持输出流的焦点,这样当我向管道发送更多命令时,它们会在远程机器而不是本地机器上执行?

1 个答案:

答案 0 :(得分:0)

我使用了paexec而不是psexec,它设法给了我一个互动会话,希望这可以帮助将来的某个人

相关问题