java 使用 pstools 远程执行exe

    在java中可以使用Runtime.getRuntime().exec命令执行外部文件。
    Pstools是一系列工具的集合 ,用于进行本机和远程机器的管理。工具包中其中包括了psexec,psfile,psgetsid,psinfo等使用工具,你可以在 http://www.microsoft.com/technet/sysinternals/FileAndDisk/PsTools.mspx
进行下载,里面还包括了一个chm格式的文档。
    下面是一个简单的使用java exec命令执行psexec的程序。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PSCaller {
    private final static String callSuccess = "with process ID";

    /**
     * Use a process to execute a command
     *
     * @param cmd
     * @return exit value
     * @throws Exception
     */
    public int execute(String cmd) throws Exception {
        int exit_code = -1;

        String ls_1;
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(p.getErrorStream()));

        while ((ls_1 = bufferedReader.readLine()) != null) {
            System.out.println("## " + ls_1);
            if (ls_1.toLowerCase().contains(callSuccess.toLowerCase())) {
                // this.setRunnerStatus(Short.valueOf("4"));
                exit_code = 0;

            }
        }

        p.waitFor();

        return exit_code;
    }

    /**
     *
     * @return pstool command
     * @throws Exception
     */
    public String createCmd() throws Exception {
        String cmd = "";
        String host = "hostname";
        // String host = "localhost";
        String bat = "notepad.exe";
        String session = "2";
        String user = "autouser";
        String password = "passwd";

        cmd += "cmd /c /"C://Program Files//pstools//psexec/" ";
        cmd += host;
        cmd += " -u ";
        cmd += user;
        cmd += " -p ";
        cmd += password;
        cmd += " -i ";
        cmd += session;
        cmd += " -d ";
        cmd += bat;

        return cmd;
    }

    public static void main(String[] args) {
        PSCaller caller = new PSCaller();
        String cmd;
        int exitnum = -1;
        try {
            cmd = caller.createCmd();
            System.out.println(cmd);
            exitnum = caller.execute(cmd);
            System.out.println("Main--" + exitnum);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值