2014-08-29 67 views
0

我有一个VB脚本,我需要传递用户名和密码。以编程方式传递Windows凭据

我想以编程方式通过Java代码运行此VB脚本。

有没有一种方法可以将Windows凭据以编程方式传递给Java脚本中的VB脚本?

+0

VB脚本是通过'Runtime.exec()'执行的吗? – 2014-08-29 16:58:52

+0

是的,我打算使用Runtime.exec运行它() – user2306856 2014-08-29 16:59:44

+0

在Runtime.exec调用期间,您不能将它们作为参数传递吗? – 2014-08-29 17:00:07

回答

-1

可以对操作系统环境的凭据,并从那里阅读:

String credentials = System.getenv().get("encrypted_credentials_or_something"); 

然后运行从Java的命令。然而,的Runtime.exec()将不会在某些情况下工作:当命令是不是在系统的PATH

  • 当参数涉及
  • 当你想访问的过程输出
  • 当您需要能够终止进程
  • 当您需要检查它是否成功终止或出错(状态码!= 0 - 这就是为什么您编写System.exit(int)来终止Java例如System.exit(1)表示异常终止)

这就是为什么我创建这个工具类来执行外部进程的参数和一切。它适用于我:

import java.io.*; 
import java.util.*; 

public class ExternalCommandHelper { 

    public static final void executeProcess(File directory, String command) throws Exception { 
     InputStreamReader in = null; 
     try { 
      //creates a ProcessBuilder with the command and its arguments 
      ProcessBuilder builder = new ProcessBuilder(extractCommandWithArguments(command)); 
      //errors will be printed to the standard output 
      builder.redirectErrorStream(true); 
      //directory from where the command will be executed 
      builder.directory(directory); 

      //starts the process 
      Process pid = builder.start(); 

      //gets the process output so you can print it if you want 
      in = new InputStreamReader(pid.getInputStream()); 

      //simply prints the output while the process is being executed 
      BufferedReader reader = new BufferedReader(in); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       System.out.println(line); 
      } 

      int status = 0; 
      //waits for the process to finish. Expects status 0 no error. Throws exception if the status code is anything but 0. 
      if ((status = pid.waitFor()) != 0) { 
       throw new IllegalStateException("Error executing " + command + " in " + directory.getAbsolutePath() + ". Error code: " + status); 
      } 

     } finally { 
      if (in != null) { 
       in.close(); 
      } 
     } 
    } 

    //Splits the command and arguments. A bit more reliable than using String.split() 
    private static String[] extractCommandWithArguments(String command) { 
     StringTokenizer st = new StringTokenizer(command); 
     String[] cmdWithArgs = new String[st.countTokens()]; 

     for (int i = 0; st.hasMoreTokens(); i++) { 
      cmdWithArgs[i] = st.nextToken(); 
     } 
     return cmdWithArgs; 
    } 
} 
相关问题