在JSch中使用SSH“ exec”通道执行sudo

时间:2018-09-24 14:38:51

标签: java shell ssh jsch

我正在使用通过以下命令传递的文件:

  1. let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let logFileURL = documentsURL.appendingPathComponent("CrashLog.txt") let string = "Hello" let data = Data(string.utf8) let fileExists = FileManager.default.fileExists(atPath: logFileURL.path) print(fileExists) do { try data.write(to: logFileURL) print("data written") } catch { print(error) }
  2. hostname
  3. pwd
  4. pbrun su - fclaim
  5. whoami
  6. cd ..

投放以下Java代码:

pwd

但是我得到以下输出:

  1. 某些主机名
  2. for (String command1 : commands) { Channel channel=session.openChannel("exec"); ((ChannelExec)channel).setCommand(command1); in=channel.getInputStream(); channel.connect(); byte[] tmp=new byte[1024]; while(true){ while(in.available()>0){ int i=in.read(tmp, 0, 1024); if(i<0) break; System.out.println(new String(tmp, 0, i)); } if(channel.isClosed()){ break; } } channel.setInputStream(null); channel.disconnect(); }
  3. 缺少输出
  4. /home/imam
  5. 缺少输出
  6. imam

2 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,并在@Martin的帮助下,大量的研发工作以及通过SO链接进行扫描后得到了解决。这是对我有用的程序。

public class SSHConn {

    static Session session;
    static String suCmds = "su - simba -c \"whoami ; pwd\"";
    static String[] commands = {"whoami", suCmds};

    public static void main(String[] args) throws Exception {
        open();
        runCmd(commands);
        close();
    }

    public static void runCmd(String[] commands) throws JSchException, IOException {
        for (String cmd : commands) {
            System.out.println("\nExecuting command: " + cmd);
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(cmd);
            InputStream in = channel.getInputStream();
            OutputStream out = channel.getOutputStream();
            channel.connect();
            //passing creds only when you switch user
            if (cmd.startsWith("su -")) {
                System.out.println("Setting suPasswd now....");
                out.write((Constants.suPasswd + "\n").getBytes());
                out.flush();
                System.out.println("Flushed suPasswd to cli...");
            }
            captureCmdOutput(in, channel);
            channel.setInputStream(null);
            channel.disconnect();
        }
    }

    public static void captureCmdOutput(InputStream in, Channel channel) throws IOException {
        System.out.println("Capturing cmdOutput now...");
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
                System.out.println(ee.getMessage());
            }
        }
    }

    public static void open() throws JSchException {
        JSch jSch = new JSch();
        session = jSch.getSession(Constants.userId, Constants.host, 22);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setPassword(Constants.userPasswd);
        System.out.println("Connecting SSH to " + Constants.host + " - Please wait for few seconds... ");
        session.connect();
        System.out.println("Connected!\n");
    }

    public static void close() {
        session.disconnect();
        System.out.println("\nDisconnected channel and session");
    }

}

输出:

Connecting SSH to my-unix-box.net - Please wait for few seconds... 
Connected!

Executing command: whoami
Capturing cmdOutput now...
john

Executing command: su - simba -c "whoami ; pwd"
Setting suPasswd now....
Flushed suPasswd to cli...
Capturing cmdOutput now...
simba
/home/simba

Disconnected channel and session

答案 1 :(得分:0)

您的代码在隔离的环境中执行每个命令。因此,第二个whoami不会像您希望的那样在pbrun su中运行。

pbrun su执行一个新的shell。

要向外壳提供命令,您可以:

通常,我建议第一种方法,因为它使用了定义更好的API(命令行参数)。