gpt4 book ai didi

java - Jsch shell/Expecdt4j 简单示例?

转载 作者:行者123 更新时间:2023-12-01 15:55:03 25 4
gpt4 key购买 nike

我正在寻找一个如何在 Jsch 中使用 Expect4j 的简单示例(使用 Shell 而不是 exec)我的意思是如何将命令(~8)发送到服务器,以及如何打印响应。

到目前为止我有这个:

  JSch jsch=new JSch();
String host="www.superserver.uk.com";
String user="tom1234";
String passwd="12345a";
Session session=jsch.getSession(user, host, 22);
session.setPassword(passwd);
session.setConfig("StrictHostKeyChecking", "no"); // if yes nothing works, but we're secure!
session.connect();
Channel channel=session.openChannel("shell");//only shell
channel.setInputStream(System.in);// enter lrp_list
channel.setOutputStream(System.out);

我想发送这样的命令:command=("lrp_list;newgrp xxx;date");发送(命令);还有一些我发现的例子只适用于时间限制;我需要像上面的代码一样执行命令,即使执行需要 15 分钟。

最佳答案

设置一个 SCPInfo 对象来保存用户名、密码、端口:22 和 IP。

    List<String> commands = new ArrayList<String>();
commands.add("touch test1.txt");
commands.add("touch test2.txt");
commands.add("touch test3.txt");
runCommands(scpInfo, commands);

public static void runCommands(SCPInfo scpInfo, List<String> commands){
try {
JSch jsch = new JSch();
Session session = jsch.getSession(scpInfo.getUsername(), scpInfo.getIP(), scpInfo.getPort());
session.setPassword(scpInfo.getPassword());
setUpHostKey(session);
session.connect();

Channel channel=session.openChannel("shell");//only shell
channel.setOutputStream(System.out);
PrintStream shellStream = new PrintStream(channel.getOutputStream()); // printStream for convenience
channel.connect();
for(String command: commands) {
shellStream.println(command);
shellStream.flush();
}

Thread.sleep(5000);

channel.disconnect();
session.disconnect();
} catch (Exception e) {
System.err.println("ERROR: Connecting via shell to "+scpInfo.getIP());
e.printStackTrace();
}
}

private static void setUpHostKey(Session session) {
// Note: There are two options to connect
// 1: Set StrictHostKeyChecking to no
// Create a Properties Object
// Set StrictHostKeyChecking to no
// session.setConfig(config);
// 2: Use the KnownHosts File
// Manually ssh into the appropriate machines via unix
// Go into the .ssh\known_hosts file and grab the entries for the hosts
// Add the entries to a known_hosts file
// jsch.setKnownHosts(khfile);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
}

关于java - Jsch shell/Expecdt4j 简单示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5247010/

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