「javajsch部署」Java jsch
本篇文章给大家谈谈javajsch部署,以及Java jsch对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
java程序执行linux命令
首先确保Linux开启sshd服务,并支持远程SSH连接。java程序使用jsch框架登录Linux,执行命令。
protected void creation() throws Exception {
JSch jsch = new JSch();
session = jsch.getSession(userName, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(CONNECT_TIMEOUT);
session.setConfig("PreferredAuthentications", "password,keyboard-interactive");
session.setServerAliveInterval(1000 * 60 * 2);
session.connect();
}
public String sendCommand(String command) throws Exception {
if(!isConnected())
throw new JSchException("Session is not connected, command exec faild.");
final ChannelExec exec = (ChannelExec)session.openChannel("exec");
ByteArrayOutputStream out = new ByteArrayOutputStream();
exec.setCommand(command);
exec.setOutputStream(out);
exec.setExtOutputStream(out);
exec.connect();
final Thread thread = new Thread() {
public void run() {
while(!exec.isEOF()) {
try { Thread.sleep(500L); } catch(Exception e) {}
}
}
};
thread.setDaemon(true);
thread.start();
thread.join(EXEC_TIMEOUT);
thread.interrupt();
if(thread.isAlive()) {
throw new JSchException("Exec Time Out Error");
} else {
try {
exec.disconnect();
out.close();
} catch (Exception e) {
}
byte[] lens = out.toByteArray();
String result = new String(lens, charset);
if(result.startsWith("bash") result.indexOf("command not found") != -1)
return "";
return result;
}
}
java如何执行远程服务器上的.sh文件
你可以使用JSch
JSch全称是“Java Secure Channel”
是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。同时也是支持执行命令;
以下是大概运行的代码,只是提供大致思路,可以去查官方API和demo
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelS;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
.......
try{
Session session = new JSch().getSession(user, ip, port);
session.setPassword(pwd);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("userauth.gssapi-with-mic", "no");
session.connect();
ChannelExec exec = (ChannelExec) session.openChannel("exec");
exec.setCommand("ifconfig");//这里是你要执行的命令,部分命令不支持,具体自己执行下
ByteArrayOutputStream bao = new ByteArrayOutputStream();
exec.setOutputStream(bao);
ByteArrayOutputStream baerr = new ByteArrayOutputStream();
exec.setErrStream(baerr);
exec.connect();
while (!exec.isEOF())
;
String errmsg = new String(baerr.toByteArray(), "utf-8");
if (StringUtils.notNull(errmsg)) {
throw new RuntimeException(errmsg);
} else {
System.out.println(new String(bao.toByteArray(), "utf-8"));
}
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭session等操作
}
java连接ssh登陆路由器
package com.flyingzl.ssh;import java.util.ArrayList
import java.util.Hashtable
import java.util.List
import org.apache.log4j.Logger
import org.apache.oro.text.regex.MalformedPatternException
import com.jcraft.jsch.ChannelShell
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import com.jcraft.jsch.UserInfo
import expect4j.Closure
import expect4j.Expect4j
import expect4j.ExpectState
import expect4j.matches.EofMatch
import expect4j.matches.Match
import expect4j.matches.RegExpMatch
import expect4j.matches.TimeoutMatch
public class Shell { private static Logger log = Logger.getLogger(Shell.class)
private Session session
private ChannelShell channel
private static Expect4j expect = null
private static final long defaultTimeOut = 1000
private StringBuffer buffer=new StringBuffer()
public static final int COMMAND_EXECUTION_SUCCESS_OPCODE = -2
public static final String BACKSLASH_R = "\r"
public static final String BACKSLASH_N = "\n"
public static final String COLON_CHAR = ":"
public static String ENTER_CHARACTER = BACKSLASH_R
public static final int SSH_PORT = 22
//正则匹配,用于处理服务器返回的结果 public static String[] linuxPromptRegEx = new String[] { "~]#", "~#", "#", ":~#", "/$", "" }
public static String[] errorMsg=new String[]{"could not acquire the config lock "}
//ssh服务器的ip地址 private String ip
//ssh服务器的登入端口 private int port
//ssh服务器的登入用户名 private String user
//ssh服务器的登入密码 private String password
public Shell(String ip,int port,String user,String password) { this.ip=ip
this.port=port
this.user=user
this.password=password
expect = getExpect()
} /** * 关闭SSH远程连接 */ public void disconnect(){ if(channel!=null){ channel.disconnect()
} if(session!=null){ session.disconnect()
} } /** * 获取服务器返回的信息 * @return 服务端的执行结果 */ public String getResponse(){ return buffer.toString()
} //获得Expect4j对象,该对用可以往SSH发送命令请求 private Expect4j getExpect() { try { log.debug(String.format("Start logging to %s@%s:%s",user,ip,port))
JSch jsch = new JSch()
session = jsch.getSession(user, ip, port)
session.setPassword(password)
HashtableString, String config = new HashtableString, String()
config.put("StrictHostKeyChecking", "no")
session.setConfig(config)
localUserInfo ui = new localUserInfo()
session.setUserInfo(ui)
session.connect()
channel = (ChannelShell) session.openChannel("shell")
Expect4j expect = new Expect4j(channel.getInputStream(), channel .getOutputStream())
channel.connect()
log.debug(String.format("Logging to %s@%s:%s successfully!",user,ip,port))
return expect
} catch (Exception ex) { log.error("Connect to "+ip+":"+port+"failed,please check your username and password!")
ex.printStackTrace()
} return null
} /** * 执行配置命令 * @param commands 要执行的命令,为字符数组 * @return 执行是否成功 */ public boolean executeCommands(String[] commands) { //如果expect返回为0,说明登入没有成功 if(expect==null){ return false
} log.debug("----------Running commands are listed as follows:----------")
for(String command:commands){ log.debug(command)
} log.debug("----------End----------")
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()
} }
ListMatch lstPattern = new ArrayListMatch()
String[] regEx = 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 { boolean isSuccess = true
for (String strCmd : commands){ isSuccess = isSuccess(lstPattern, strCmd)
} //防止最后一个命令执行不了 isSuccess = !checkResult(expect.expect(lstPattern))
//找不到错误信息标示成功 String response=buffer.toString().toLowerCase()
for(String msg:errorMsg){ if(response.indexOf(msg)-1){ return false
} } return isSuccess
} catch (Exception ex) { ex.printStackTrace()
return false
} } //检查执行是否成功 private boolean isSuccess(ListMatch 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
} } //检查执行返回的状态 private boolean checkResult(int intRetVal) { if (intRetVal == COMMAND_EXECUTION_SUCCESS_OPCODE) { return true
} return false
} //登入SSH时的控制信息 //设置不提示输入密码、不显示登入信息等 public static class localUserInfo implements UserInfo { String passwd
public String getPassword() { return passwd
} public boolean promptYesNo(String str) { return true
} public String getPassphrase() { return null
} public boolean promptPassphrase(String message) { return true
} public boolean promptPassword(String message) { return true
} public void showMessage(String message) { } }}
javajsch部署的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于Java jsch、javajsch部署的信息别忘了在本站进行查找喔。
发布于:2022-12-14,除非注明,否则均为
原创文章,转载请注明出处。