0

如何在java中获取和创建Linux pc上文件的访问权限、组和用户。

4

2 回答 2

0
package Test.Dir.Onlinux;

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import ch.ethz.ssh2.Connection;  
import ch.ethz.ssh2.Session;  
import ch.ethz.ssh2.StreamGobbler;  
import java.lang.System;

public class TestDirOnLinux {


    public static void main(String[] args) {

        String linuxCommands[] = { "stat -c %U ", "stat -c %G ", "stat -c %A ", "stat -c %a " };
        String fileName = "/home/zmt/UberSVN";
        excuteLinuxCommand("192.168.0.26", "root", "ace@dir", linuxCommands[0] + fileName);
        excuteLinuxCommand("192.168.0.26", "root", "ace@dir", linuxCommands[1] + fileName);
        excuteLinuxCommand("192.168.0.26", "root", "ace@dir", linuxCommands[2] + fileName);
        excuteLinuxCommand("192.168.0.26", "root", "ace@dir", linuxCommands[3] + fileName);
    }

    public static void excuteLinuxCommand(String ipAddress, String userName, String password, String linuxCommands) {

        boolean isAuthenticated = false;

        try {
            // Connection conn = new Connection(hostname);
            Connection conn = new Connection(ipAddress);
            conn.connect();
            // isAuthenticated = conn.authenticateWithPassword(username,
            // password);
            isAuthenticated = conn.authenticateWithPassword(userName, password);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

            Session sess = conn.openSession();

            // sess.execCommand("shutdown -h now");
            sess.execCommand(linuxCommands);

            InputStream stdout = new StreamGobbler(sess.getStdout());
            InputStream stderr = new StreamGobbler(sess.getStderr());

            InputStreamReader insrout = new InputStreamReader(stdout);
            InputStreamReader insrerr = new InputStreamReader(stderr);

            BufferedReader stdoutReader = new BufferedReader(insrout);
            BufferedReader stderrReader = new BufferedReader(insrerr);

            while (true) {
                String line = stdoutReader.readLine();`enter code here`
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }

            while (true) {
                String line = stderrReader.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }

            sess.close();

            conn.close();

        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(2);
        }
    }
}

    enter code here
于 2013-02-21T04:42:30.857 回答
0

如果您使用的是 Java 7,则应该能够使用POSIX 功能来执行此操作。具体来说,该getPosixFilePermissions方法应该是您正在寻找的。有关更多信息,请参阅此问题

于 2013-02-20T16:15:57.587 回答