因此,要执行这些容易增加的任务,如果您敢使用Jsch ( any文档),这似乎是不可能的,在Jsch、sshj、Ganymed之间有选择吗?
神秘:
2)输入多个命令
4)在现有的txt文件中添加更多的txt :D (可能是命令中的构建),还是不添加?
/* just for download/owerride : sftpChannel.get("downloadfile.txt", "savefile.txt");*/发布于 2011-02-24 01:26:22
我不能对其他人发表评论,但甘尼德的工作确实很好。
发布于 2011-02-24 04:30:09
我不知道甘尼德的事。但是我已经在远程登录和脚本执行中广泛使用了JSch。我在expect模式(发送/等待)中使用Google的Expect4j和Jsch在远程机器上执行脚本。您可以使用JSch/Expet4j/闭包在代码中获得执行的命令或脚本的全部输出。
对于jsch,请转到http://www.jcraft.com/jsch/
对于Expect4j,请转到http://code.google.com/p/expect4j/
下面是一个用于远程Java类登录和执行文件的小代码示例。
private Expect4j SSH(String hostname, String username,String password, int port) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, port);
if (password != null) {
session.setPassword(password);
}
Hashtable<String,String> config = new Hashtable<String,String>();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(60000);
channel = (ChannelShell) session.openChannel("shell");
Expect4j expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
channel.connect();
return expect;
}此方法将打开一个SSH流到远程服务器,expect4j将使用该流发送命令。
private boolean executeCommands() {
boolean isSuccess = true;
Closure closure = new Closure() {
public void run(ExpectState expectState) throws Exception {
buffer.append(expectState.getBuffer());//buffer is string buffer for appending output of executed command
expectState.exp_continue();
}
};
List<Match> lstPattern = new ArrayList<Match>();
String[] regEx = SSHConstants.linuxPromptRegEx;
if (regEx != null && regEx.length > 0) {
synchronized (regEx) {
for (String regexElement : regEx) {//list of regx like, :>, /> etc. it is possible command prompts of your remote machine
try {
RegExpMatch mat = new RegExpMatch(regexElement, closure);
lstPattern.add(mat);
} catch (MalformedPatternException e) {
return false;
} catch(Exception e) {
return false;
}
}
lstPattern.add(new EofMatch( new Closure() { // should cause entire page to be collected
public void run(ExpectState state) {
}
}));
lstPattern.add(new TimeoutMatch(defaultTimeOut, new Closure() {
public void run(ExpectState state) {
}
}));
}
}
try {
Expect4j expect = SSH(objConfig.getHostAddress(), objConfig.getUserName(), objConfig.getPassword(), SSHConstants.SSH_PORT);
expect.setDefaultTimeout(defaultTimeOut);
if(isSuccess) {
for(String strCmd : lstCmds)
isSuccess = isSuccess(lstPattern,strCmd);
}
boolean isFailed = checkResult(expect.expect(lstPattern));
return !isFailed;
} catch (Exception ex) {
return false;
} finally {
closeConnection();
}
}
private boolean isSuccess(List<Match> objPattern,String strCommandPattern) {
try {
boolean isFailed = checkResult(expect.expect(objPattern));
if (!isFailed) {
expect.send(strCommandPattern);
expect.send("\r");
return true;
}
return false;
} catch (MalformedPatternException ex) {
return false;
} catch (Exception ex) {
return false;
}
} https://stackoverflow.com/questions/5097514
复制相似问题