jsch连接Linux工具类
import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.*; /**
* Created by solon on 2017/3/1.
* 远程调用工具
*/
public class SSHBase {
String host;
String user;
Session session;
UserInfo ui; final Logger logger = LoggerFactory.getLogger(SSHBase.class); public SSHBase(String host, String user, String passwd) {
this.host = host;
this.user = user;
this.ui = new MyUserInfo(passwd);
} public void connect() {
try {
JSch jsch = new JSch(); this.session = jsch.getSession(this.user, this.host, 22);
this.session.setUserInfo(this.ui);
this.session.connect();
logger.info("connect to {}@{} success.", this.user, this.host);
} catch (JSchException e) {
logger.error("connect to {} failed.", this.host, e);
}
} public String runCommand(String cmd) {
Channel channel = null;
StringBuffer cmdOutput = new StringBuffer();
int cmdExitStatus = -1;
boolean isSuccess = false;
JSONObject result = new JSONObject();
result.put("result",isSuccess);
result.put("output",cmdOutput.toString());
result.put("exitStatus",cmdExitStatus);
try {
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(cmd); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024];
logger.info("run \"{}\"", cmd);
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
cmdOutput.append(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (in.available() > 0) continue;
cmdExitStatus = channel.getExitStatus();
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error("run \"{}\" thread sleep error", cmd, e);
return result.toString();
}
}
logger.info("{} output is:{}", cmd, cmdOutput);
logger.info("{} ExitStatus is:{}", cmd, cmdExitStatus);
} catch (JSchException e1) {
logger.error("run \"{}\"", cmd, e1);
return result.toString();
} catch (IOException e1) {
logger.error("run \"{}\"", cmd, e1);
return result.toString();
} finally
{
if (channel != null) {
channel.disconnect();
}
}
isSuccess = true;
result.put("result",isSuccess);
result.put("output", cmdOutput.toString());
result.put("exitStatus", cmdExitStatus);
return result.toString();
} public boolean scpToRemote(String srcFile, String dstFile) {
Channel channel = null;
try {
FileInputStream fis = null;
boolean ptimestamp = true; // exec 'scp -t rfile' remotely
String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + dstFile;
channel = this.session.openChannel("exec");
((ChannelExec) channel).setCommand(command); // get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream(); channel.connect(); if (checkAck(in) != 0) {
logger.error("scp {} check ack failed.", srcFile);
return false;
} File _lfile = new File(srcFile); if (ptimestamp) {
command = "T " + (_lfile.lastModified() / 1000) + " 0";
// The access time should be sent here,
// but it is not accessible with JavaAPI ;-<
command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
logger.error("scp {} check ack failed.", srcFile);
return false;
}
} // send "C0644 filesize filename", where filename should not include '/'
long filesize = _lfile.length();
command = "C0644 " + filesize + " ";
if (srcFile.lastIndexOf('/') > 0) {
command += srcFile.substring(srcFile.lastIndexOf('/') + 1);
} else {
command += srcFile;
}
command += "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
logger.error("scp {} check ack failed.", srcFile);
return false;
} // send a content of lfile
fis = new FileInputStream(srcFile);
byte[] buf = new byte[1024];
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0) break;
out.write(buf, 0, len); //out.flush();
}
fis.close();
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
logger.error("scp {} check ack failed.", srcFile);
return false;
}
out.close();
channel.disconnect();
} catch (JSchException e) {
logger.error("scp {} failed.", srcFile, e);
return false;
} catch (IOException e) {
logger.error("scp {} failed.", srcFile, e);
return false;
} finally {
if (channel != null) {
channel.disconnect();
}
}
return true;
} public void close() {
if (this.session != null) {
this.session.disconnect();
}
} public class MyUserInfo implements UserInfo {
String passwd; public MyUserInfo(String passwd) {
this.passwd = 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) {
logger.info(message);
} } int checkAck(InputStream in) throws IOException {
int b = in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if (b == 0) return b;
if (b == -1) return b; if (b == 1 || b == 2) {
StringBuffer sb = new StringBuffer();
int c;
do {
c = in.read();
sb.append((char) c);
}
while (c != '\n');
if (b == 1) { // error
logger.error(sb.toString());
}
if (b == 2) { // fatal error
logger.error(sb.toString());
}
}
return b;
} }
jsch连接Linux工具类的更多相关文章
- 第2章 Linux系统安装(3)_SSH连接Linux工具:SecureCRT和WinSCP
4. SSH连接Linux工具 4.1 Linux网卡配置 (1)临时配置: ifconfig eth0 192.168.32.100 //给eth0网卡指定IP,写在ROM里的,关机会丢失. (2) ...
- Druid连接池工具类
package cn.zmh.PingCe; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSo ...
- Android OkHttp网络连接封装工具类
package com.lidong.demo.utils; import android.os.Handler; import android.os.Looper; import com.googl ...
- java使用jsch连接linux
由于项目需要使用java来linux进行管理,近一番查找,发现第三方jar包 jsch 可以轻松实现对linux的管理,(相关文档及例子请访问官网www.jcraft.com),故引进. 在网上搜索了 ...
- 基于JSch的Sftp工具类
本Sftp工具类的API如下所示. 1)构造方法摘要 Sftp(String host, int port, int timeout, String username, String password ...
- jdbc连接的工具类
在不实用框架的情况下,有一个jdbc的工具类来进行数据库的连接就再好不过了,下面提供这个工具类DBUtil.java package org.jdbc.test; import java.io.Inp ...
- C3P0连接池工具类使用
c3p0的基本连接配置文件 c3p0-config.xml <c3p0-config> <default-config> <property name="dri ...
- C3P0连接池工具类实现步骤及方法
C3P0连接池的工具类 使用C3P0获得连接对象连接池有一个规范接口 javax.sal.DataSourse 接口定义了一个从连接池中获得连接的方法getConnection(); 步骤导入jar包 ...
- JDBC连接Oracle工具类
import java.sql.*;import java.util.ResourceBundle; /** * jdbc工具类,负责: * 1. 加载/注册数据库驱动程序 * 2. 获取数据库连接 ...
随机推荐
- React中state和props的区别
props和state都是用于描述component状态的,并且这个状态应该是与显示相关的. State 如果component的某些状态需要被改变,并且会影响到component的render,那么 ...
- UE mac版16.10.0.22破解
http://bbs.feng.com/read-htm-tid-10828753.html 去官网下载原载,先运行一次,再在终端里执行下面代码就可以破解完成! printf '\x31\xC0\xF ...
- Ubuntu 使用 heirloom-mail 调用外部邮箱 SMTP 服务器发送邮件
使用本地服务发邮件,经常被过滤掉而且占用资源,发送成功率不高.所以使用外部SMTP服务器发送邮件成为了需求. SMTP认证的目的是为了使用户避免受到垃圾邮件的侵扰,简单地说就是要求必须在提供了账户名和 ...
- unreal3对象管理模块分析
凡是稍微大一点的引擎框架,必然都要自己搞一套对象管理机制,如mfc.qt.glib等等,unreal自然也不例外. 究其原因,还是c++这种静态语言天生的不足,缺乏运行时类型操作功能,对于复杂庞大的逻 ...
- JavaScript基础:
一. JavaScript概述 JavaScript一种直译式脚本语言,是一种动态类型.弱类型.基于原型的语言,内置支持类型. document.write("<h1>这是一个标 ...
- 微观SOA:服务设计原则及其实践方式
大 量互联网公司都在拥抱SOA和服务化,但业界对SOA的很多讨论都比较偏向高大上.本文试图从稍微不同的角度,以相对接地气的方式来讨论SOA, 集中讨论SOA在微观实践层面中的缘起.本质和具体操作方式, ...
- java类什么时候初始化?
Java虚拟机规范中并没有进行强制玉树什么情况下需要开始类加载过程.但是对于初始化阶段,虚拟机规范则是严格规定了有且仅有5种情况必须立即对类进行“初始化”(而加载,验证,准备自然需要在此之前开始): ...
- 19.Imagetragick 命令执行漏洞(CVE-2016–3714)
Imagetragick 命令执行漏洞(CVE-2016–3714) 漏洞简介: Imagetragick 命令执行漏洞在16年爆出来以后,wooyun上面也爆出了数个被该漏洞影响的大厂商,像腾讯, ...
- EIP权限工作流平台总结-4跨域配置
1.预览地址:www.eipflow.com (1) 权限工作流:www.demo.eipflow.com/Account/Login (2) 基础权限版:www.auth.eipflow.com/A ...
- 2017-10-12 NOIP模拟赛
斐波那契 /* 相同颜色的节点与父亲节点的差相等,且是一个小于它的最大斐波那契数 所以降两个点同时减去小与它的最大斐波那契数,直到两点相等 */ #include<cstdio> ; ...