【发布时间】:2015-06-09 12:41:21
【问题描述】:
我是 Java 新手(我仍在学习过程中),所以如果您的回答提供了我可以遵循的详细步骤,我将不胜感激。
这就是我要找的 1) 我在 txt 文件中有一个命令列表。 2)我在另一个文件中有一个服务器列表。 3) 我希望让 java 程序提示输入我的 SSH 用户 ID/密码,加载命令文件和服务器文件。并在有问题的服务器上执行命令。 4) 将输出存储在本地机器上的 txt 文件中,稍后我会解析。
我能够让以下 Java 程序登录并运行一些推荐。但正如您所看到的,UID/密码和一个服务器只存储在程序中,我只读取 System.out 而不将输出写入文件。
请帮忙!!!
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/** Demonstrates a connection to a remote host via SSH. **/
public class JSSH
{
private static final String user = "UID"; // TODO: Username of ssh account on remote machine
private static final String host = "localhost"; // TODO: Hostname of the remote machine (eg: inst.eecs.berkeley.edu)
private static final String password = "pass"; // TODO: Password associated with your ssh account
private static final String command = "ls -l\n cd Downloads \n ls -l\n"; // Remote command you want to invoke
public static void main(String args[]) throws JSchException, InterruptedException
{
JSch jsch = new JSch();
// TODO: You will probably want to use your client ssl certificate instead of a password
// jsch.addIdentity(new File(new File(new File(System.getProperty("user.home")), ".ssh"), "id_rsa").getAbsolutePath());
Session session = jsch.getSession(user, host, 22);
// TODO: You will probably want to use your client ssl certificate instead of a password
session.setPassword(password);
// Not recommended - skips host check
session.setConfig("StrictHostKeyChecking", "no");
// session.connect(); - ten second timeout
session.connect(10*1000);
Channel channel = session.openChannel("shell");
// TODO: You will probably want to use your own input stream, instead of just reading a static string.
InputStream is = new ByteArrayInputStream(command.getBytes());
channel.setInputStream(is);
// Set the destination for the data sent back (from the server)
// TODO: You will probably want to send the response somewhere other than System.out
channel.setOutputStream(System.out);
// channel.connect(); - fifteen second timeout
channel.connect(15 * 1000);
// Wait three seconds for this demo to complete (ie: output to be streamed to us).
Thread.sleep(3*1000);
// Disconnect (close connection, clean up system resources)
channel.disconnect();
session.disconnect();
}
}
【问题讨论】: