Java Jsch sudo作为用户并执行脚本

时间:2017-08-28 11:50:01

标签: java unix sudo jsch

使用jsch我已登录到远程主机,以不同的用户身份执行脚本。 必须使用“exec”频道。 当前的unix动作我做的是:    1)sudo su -    2)运行脚本

如何运行此命令“sudo su - ”然后在同一通道中执行脚本

更新了代码注释,我尝试将以下两个命令作为输入发送。它在循环中运行,我没有看到它正在执行。以下tw是数组列表“命令”中发送的输入 sudo su - testusr /home/testusr/start.sh

ChannelShell channel = null;

List<String> result = new ArrayList<String>();
InputStream inStream = null;
OutputStream outStream = null;

PipedOutputStream pOutStream = null;
PipedInputStream pInStream = null;
try {
    inStream = new PipedInputStream();
    pOutStream = new PipedOutputStream((PipedInputStream) inStream);

    outStream = new PipedOutputStream();
    pInStream = new PipedInputStream((PipedOutputStream) outStream);
    channel = (ChannelShell) session.openChannel("shell");
    // channel.setPty(true);
    channel.setInputStream(inStream);
    channel.setOutputStream(outStream);
    channel.connect();
    BufferedReader bfs = null;

    for (String command : commands) {
        LOGGER.info("Executing command {} ", command);
        pOutStream.write((command.concat("\n")).getBytes());
    }
    LOGGER.info(" exit status {}", channel.getExitStatus());
    bfs = new BufferedReader(new InputStreamReader((inStream)));
    if (channel.getExitStatus() != 0) {

        result.add("ERROR");
    }
    String line;
    byte[] bt = new byte[1024];
    while (true) {
        while (inStream.available() > 0) {
            int i = inStream.read(bt, 0, 1024);
            if (i < 0) {
                break;
            }
            LOGGER.info("result {}", new String(bt, 0, i));
        }
        if (channel.isClosed()) {
            LOGGER.info("exit status {}", channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2ED EDIT

for (String command : commands) {
                OutputStream out = channel.getOutputStream();
                out.write((command.concat("\n")).getBytes());
                out.flush();
                InputStream in = channel.getInputStream();
                byte[] tmp = new byte[1024];
                while (true) {
                    while (in.available() > 0) {
                        int i = in.read(tmp, 0, 1024);
                        if (i < 0) {
                            break;
                        }
                        LOGGER.info("Output stream execution {}", new String(
                                tmp, 0, i));
                    }
                    if (channel.isClosed()) {
                        LOGGER.info("Executing exit status {}",
                                channel.getExitStatus());
                        break;
                    }
                }
            }

1 个答案:

答案 0 :(得分:0)

你真的需要做sudo su -吗? 如果您的脚本是bash脚本,则可以致电sudo bash your_script.sh

这适用于更改解释器的任何脚本类型。

su -恢复用户环境,如果您确实需要,您的脚本可能会提供~/.bash_profile

相关问题