1

我想将端口号映射到用户(正在运行绑定到端口的进程的 Linux 用户)。我怎样才能在java中做到这一点?

我知道我可以进入 shell 并运行将端口映射到 PID,然后将 PID 映射到用户的 bash 命令,但如果可以的话,我想将它保存在 java 中。

更普遍的问题是:我有一个从 localhost 接收请求的 webapp 应用程序,我想知道哪个本地用户执行了 HttpServletRequest,因此我可以为其附加适当的权限。

背景:

我正在为所有远程连接使用弹簧安全性。但是,我有一小部分应用程序(与 webapp 分离)在本地与应用程序服务器一起运行,并且该应用程序使用 linux 用户机制进行身份验证。因此,出于这个原因,我绕过了 localhost 的服务器身份验证规则(假设允许所有 localhost 访问)。问题在于授权 - 我需要识别运行 localhost 请求的用户。知道如何实现这一目标吗?

4

1 回答 1

0

This is Linux dependent code, but not difficult to port to Windows.

This is not a Servlet code, but would work in that case as well:

Lets say I've a ServerSocket waiting on accept() call. When it receives a client request, it creates a Socket at another port to deal with that 'remote' request.

ServerSocket ss = new ServerSocket(2000);
System.out.println("Listening on local port : " + ss.getLocalPort());

while(...)
{
 Socket s = ss.accept();
 System.out.println("accepted client request, opened local port : " + s.getPort());
 ...
}

So, you need to feed the output of s.getPort() from above snippet to the following program's main() method.

public class FindUserByPort
{
  public static void main(String[] args) throws Exception
  {
    String cmd = "netstat -anp | grep ";
    int port = Integer.valueOf(args[0]);
    cmd = cmd + port ;

    Process pr = Runtime.getRuntime().exec(cmd);
    InputStream is = pr.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = null;
    List<Integer> pIDs = new ArrayList<Integer>();

    while ((line = br.readLine()) != null)
    {
      if (line.contains("127.0.0.1:" + port))
      {
        String pidPname = line.substring(line.indexOf("ESTABLISHED") + "ESTABLISHED".length());
        pidPname = pidPname.trim();
        String pid = pidPname.split("/")[0];
        pIDs.add(Integer.valueOf(pid));
      }
    }
    if (pIDs.size() > 0)
    {
      for (int pid : pIDs)
      {
        String command = "top -n1 -b -p " + pid ;
        Process p = Runtime.getRuntime().exec(command);
        InputStream _is = p.getInputStream();

        BufferedReader _br = new BufferedReader(new InputStreamReader(_is));
        String _line = null;
        while ((_line = _br.readLine()) != null)
        {
          _line = _line.trim();
          if(_line.startsWith(String.valueOf(pid)))
          {
            String[] values = _line.split(" ");
            System.out.println("pid : " + pid + ", user : " + values[1]);
          }
        }
        _is.close();
        _br.close();
      }
    }
    is.close();
    br.close();
  }
}
于 2013-07-30T08:29:16.117 回答