通过 java 进行 ssh

发布于 2024-11-01 19:07:54 字数 2919 浏览 4 评论 0原文

我正在使用 java ssh 工具与我的学校帐户建立 ssh 连接并查找文件,然后将其删除。然而,我正在创建三个函数来执行相同的操作,但使用不同的文件,我正在寻找一种方法来执行同一操作,而不是一个接一个地执行。这是一些代码。基本上我想知道是否有一种方法可以在一个 ssh 连接或某种 fork 或多线程上完成这一切。

public void updateinterval() {
    try {
        JSch jsch = new JSch();

        String user = "***********";
        String host = "********";
        Session session = jsch.getSession(user, host, 22);

        session.setPassword("*********");

        // username and password will be given via UserInfo interface.
        UserInfo userInfo = new SftpUserInfo();

        session.setUserInfo(userInfo);

        session.connect();

        // look for a file named feedinterval

        String checkfortimeupdate =
                "cd public_html/final;grep '-send' feedinterval";

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(checkfortimeupdate);

        // X Forwarding
        // channel.setXForwarding(true);

        // channel.setInputStream(System.in);
        channel.setInputStream(null);

        // channel.setOutputStream(System.out);

        // FileOutputStream fos=new FileOutputStream("/tmp/stderr");
        // ((ChannelExec)channel).setErrStream(fos);
        ((ChannelExec) channel).setErrStream(System.err);

        InputStream 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;
                String returned = new String(tmp, 0, i);

                String argument = returned.substring(6);

                if (returned.contains("-send")) {

                    // if its there its calls the removeinterval function
                    // which removes the file it found
                    // by doing the same thing this function does but with a
                    // different ssh command

                    arduinoupdate hey = new arduinoupdate();

                    hey.removeinterval();

                    try {
                        Runtime rt = Runtime.getRuntime();

                        String[] commands = {
                                "system.exe", "-send", argument };

                        Process proc = rt.exec(commands);
                    }

                    catch (IOException e) {
                    }
                }
            }

            if (channel.isClosed()) {
                System.out.println("UpdateInterval Closed exit-status: "
                        + channel.getExitStatus());
                break;
            }
            try {
                /* Thread.sleep(1000); */
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
    } catch (Exception e) {
        System.out.println(e);
    }
}

I am using java ssh tools to make an ssh connection to my school account and look for a file and then delete it. However I am creating three functions to do the same thing but with different files, I am looking for a way to do that at the same thing instead of doing one after the other. Here is some code. Basically I want to know if there is a way to do this all on one ssh connection or some kind of fork or multithreading.

public void updateinterval() {
    try {
        JSch jsch = new JSch();

        String user = "***********";
        String host = "********";
        Session session = jsch.getSession(user, host, 22);

        session.setPassword("*********");

        // username and password will be given via UserInfo interface.
        UserInfo userInfo = new SftpUserInfo();

        session.setUserInfo(userInfo);

        session.connect();

        // look for a file named feedinterval

        String checkfortimeupdate =
                "cd public_html/final;grep '-send' feedinterval";

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(checkfortimeupdate);

        // X Forwarding
        // channel.setXForwarding(true);

        // channel.setInputStream(System.in);
        channel.setInputStream(null);

        // channel.setOutputStream(System.out);

        // FileOutputStream fos=new FileOutputStream("/tmp/stderr");
        // ((ChannelExec)channel).setErrStream(fos);
        ((ChannelExec) channel).setErrStream(System.err);

        InputStream 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;
                String returned = new String(tmp, 0, i);

                String argument = returned.substring(6);

                if (returned.contains("-send")) {

                    // if its there its calls the removeinterval function
                    // which removes the file it found
                    // by doing the same thing this function does but with a
                    // different ssh command

                    arduinoupdate hey = new arduinoupdate();

                    hey.removeinterval();

                    try {
                        Runtime rt = Runtime.getRuntime();

                        String[] commands = {
                                "system.exe", "-send", argument };

                        Process proc = rt.exec(commands);
                    }

                    catch (IOException e) {
                    }
                }
            }

            if (channel.isClosed()) {
                System.out.println("UpdateInterval Closed exit-status: "
                        + channel.getExitStatus());
                break;
            }
            try {
                /* Thread.sleep(1000); */
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
    } catch (Exception e) {
        System.out.println(e);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

枯叶蝶 2024-11-08 19:07:54

如果您想运行多个任务,也许 ExpectJ 会更适合您。 ExpectJ 在幕后使用 JSCH,因此这可能会让您的生活更轻松。

final ExpectJ expectJ = new ExpectJ();
final Spawn spawn = expectJ.spawn("host", 22, "user", "pass");
spawn.send("cd public_html/final\n");
spawn.expect("someReturn");
...
spawn.send("exit\n");
spawn.expectClose();

If you want to run multiple tasks perhaps ExpectJ would work better for you. ExpectJ uses JSCH under the covers, so this may make your life easier.

final ExpectJ expectJ = new ExpectJ();
final Spawn spawn = expectJ.spawn("host", 22, "user", "pass");
spawn.send("cd public_html/final\n");
spawn.expect("someReturn");
...
spawn.send("exit\n");
spawn.expectClose();
风启觞 2024-11-08 19:07:54

正如评论者所说,最好将其分解为单独的函数。
然后更清楚如何重用相同的连接(即 会话)用于多个命令。

public void updateInterval(Session s, String filename) {
    String checkfortimeupdate = "fgrep '-send' \"public_html/final/" + filename + "\"";

    ChannelExec channel = (ChannelExec)session.openChannel("exec");
    channel.setCommand(checkfortimeupdate);

    channel.setInputStream(null);
    channel.setErrStream(System.err);
    BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream(), encoding));

    channel.connect();

    eatOutput(in);

    if (channel.isClosed()) {
        System.out.println("UpdateInterval Closed exit-status: "
                           + channel.getExitStatus());
        break;
    }
    channel.disconnect();
}

然后将从 BufferedReader 读取的内容(它有一个 readLine 方法)放入 eatOutput 方法中,并使用另一个方法来打开会话并调用此处显示的方法三倍(使用不同的文件名),然后再次关闭会话。

As said by the commenters, better factor it out in separate functions.
Then is gets more clear how to reuse the same connection (i.e. Session) for several commands.

public void updateInterval(Session s, String filename) {
    String checkfortimeupdate = "fgrep '-send' \"public_html/final/" + filename + "\"";

    ChannelExec channel = (ChannelExec)session.openChannel("exec");
    channel.setCommand(checkfortimeupdate);

    channel.setInputStream(null);
    channel.setErrStream(System.err);
    BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream(), encoding));

    channel.connect();

    eatOutput(in);

    if (channel.isClosed()) {
        System.out.println("UpdateInterval Closed exit-status: "
                           + channel.getExitStatus());
        break;
    }
    channel.disconnect();
}

Then put the reading from the BufferedReader (it has a readLine method) in the method eatOutput, and have another method which opens the session and calls three times the method shown here (with different file names), and closes the session again.

云朵有点甜 2024-11-08 19:07:54

关于ExpectJ的使用,
哪个是在机器关键生产应用程序中用于基于期望的功能的最佳库?

ExpectJ 或 Expect4J 库?不过,这两个库都使用了 JSch!
或者 Apache SSHD - 客户端:

SshClient client = SshClient.setUpDefaultClient(); PipedOutputStream PipedIn...?

In respect to the usage of ExpectJ,
which is the best library to use in machine critical production application for expect based functionality?

ExpectJ or Expect4J library? Though, both library uses the JSch underneath!
Or Apache SSHD - Client:

SshClient client = SshClient.setUpDefaultClient(); PipedOutputStream PipedIn...?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文