Linux命令" logname"不在java工作

时间:2014-05-15 10:35:31

标签: java linux terminal ubuntu-14.04

我正在使用Ubuntu 14.04,我尝试从java执行logname命令作为sudo用户,但它返回null。我尝试的代码如下:

try {            
        Process p = Runtime.getRuntime().exec("logname");
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String sa = br.readLine();
        System.out.println("Logged User: "+sa);
    } catch (IOException ex) {
        System.out.println(ex);
    }  

我得到的输出是

  

记录用户:null

我也试过

  

String [] temp = {" / bin / sh"," -c"," logname"} exec(temp);

     

String [] temp = {" / bin / sh"," -c"," sudo logname"} exec(temp);

     

exec(" sudo logname");

更新1:

我试过了whoami | awk' {print $ 1}'用于查找日志名称。但那没用。如果我以root身份登录,则显示root。

2 个答案:

答案 0 :(得分:1)

您是否尝试使用要尝试执行的应用程序的完整路径?

/usr/bin/logname

/usr/bin/whoami

如何使用:

"echo $SUDO_USER"

这似乎有效:

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

public class runlogname {

    public static void main(String[] args) 
    {
    try 
        {
        ProcessBuilder pb = new ProcessBuilder();
        pb.command("/bin/bash", "-c", "/usr/bin/logname").start();
        Process p = pb.start();
        int retValue = p.waitFor();
        System.out.println("retValue = " + Integer.toString(retValue));

        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        StringBuffer output = new StringBuffer();
        String line = "";           
        while ((line = br.readLine())!= null) {
            output.append(line + "\n");
        }

        String sa = output.toString();
        System.out.println("Logged User: "+sa);
        } 
    catch (IOException ex) 
        {
        System.out.println(ex);
        }
    catch (InterruptedException ex)
        {
        System.out.println(ex);
        }
    }
}

但是logname命令返回返回码1,该命令根据手册页显示错误。所以这意味着java代码是正确的但是logname命令不起作用。

我提供的示例运行strace(带-f标志)将告诉您失败的原因。

在我的盒子上是:

[pid 29925] write(2, "/usr/bin/logname: ", 18) = 18
[pid 29925] write(2, "no login name", 13) = 13
[pid 29925] write(2, "\n", 1)           = 1

答案 1 :(得分:0)

尝试用“/ bin / bash”替换“/ bin / sh”。如果你有Ubuntu,你可能有bash shell,而不是sh。