程序示例
static void pkexecGui() throws Exception {
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("pkexec env DISPLAY=:0 XAUTHORITY=/home/yeqiang/.Xauthority filezilla");
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("");
while ((line = br.readLine()) != null)
System.out.println(line);
System.out.println(" ");
isr = new InputStreamReader(proc.getErrorStream());
br = new BufferedReader(isr);
System.out.println("");
while ((line = br.readLine()) != null)
System.out.println(line);
System.out.println(" ");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}
}
注意
pkexec运行默认加载的环境变量没有设置显示参数,会导致打不开DISPLAY,通过pkexec env参数注入,关键代码
pkexec env DISPLAY=:0 XAUTHORITY=/home/yeqiang/.Xauthority filezilla
其中
env DISPLAY=:0 XAUTHORITY=/home/yeqiang/.Xauthority
为传递给pkexec的环境变量参数
末尾的filezilla为一个图形界面程序,输入正确密码后,可以在root权限下运行filezilla



