使用Linux Terminal运行命令的Java程序

使用Linux Terminal运行命令的Java程序,第1张

使用Linux Terminal运行命令的Java程序

您可以“读取”过程输入,并在“检测到”密码提示时显示,

JOptionPane
并要求用户输入密码。

在开始该过程之前,您“可以”提示用户输入密码,因为您知道需要将其发送给该过程。

您可能仍然需要监视进程的输出,以确定何时需要发送密码。

让我们从…开始

Runtime.getRuntime().exec("sudo python ./flashimage.py");

您完全忽略了

Process
。您也不处理输出,但是您没有办法向流程提供输入…

通常,

Runtime#exec
充其量是有问题的。您最好使用
ProcessBuilder
....

// Build the command to be executed.  Note that each parameter becomes// it's own argument, this deals with parameters that contain spaces// much better then Runtime#exec alone...ProcessBuilder pb = new ProcessBuilder("sudo", "python", "./flashimage.py");pb.redirectError();InputStream is = null;try {    Process p = pb.start();    is = p.getInputStream();    StringBuilder output = new StringBuilder(80);    int in = -1;    while ((in = is.read()) != -1) {        if (in != 'n') { output.append((char)in); // You will need to define PASSWORD_prompt if (PASSWORD_prompt.equals(output.toString())) {     String text = JOptionPane.showInputDialog("Password");     OutputStream os = p.getOutputStream();     os.write(text.getBytes()); }        } else { System.out.println(output.toString()); output.delete(0, output.length());        }    }} catch (IOException exp) {    exp.printStackTrace();} finally {    try {        is.close();    } catch (Exception e) {    }}

现在,毫无疑问,有人会指出(至少)这种方法有两个问题……

  1. JOptionPane.showInputDialog("Password");
    将显示一个法线
    JTextField
    ,不会隐藏密码字符和
  2. String
    不是最安全的密码存储方式…

相反,我们应该使用

JPasswordField
并将结果
char
数组转换为
byte
数组…

JPasswordField password = new JPasswordField(10);JLabel label = new JLabel("Password: ");JPanel panel = new JPanel();panel.add(label);panel.add(password);int option = JOptionPane.showConfirmDialog(null, panel, "Password", JOptionPane.OK_CANCEL_OPTION);if (option == JOptionPane.OK_OPTION) {    char[] userPassword = password.getPassword();    byte[] bytes = new byte[userPassword.length * 2];    for (int i = 0; i < userPassword.length; i++) {        bytes[i * 2] = (byte) (userPassword[i] >> 8);        bytes[i * 2 + 1] = (byte) userPassword[i];    }    os.write(bytes);}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5012405.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存