gpt4 book ai didi

java - 通过 java 进行 ssh

转载 作者:行者123 更新时间:2023-12-01 15:52:51 24 4
gpt4 key购买 nike

我正在使用 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);
}
}

最佳答案

如果你想运行多个任务也许 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();

关于java - 通过 java 进行 ssh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5670244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com