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工具类的更多相关文章

  1. 第2章 Linux系统安装(3)_SSH连接Linux工具:SecureCRT和WinSCP

    4. SSH连接Linux工具 4.1 Linux网卡配置 (1)临时配置: ifconfig eth0 192.168.32.100 //给eth0网卡指定IP,写在ROM里的,关机会丢失. (2) ...

  2. Druid连接池工具类

    package cn.zmh.PingCe; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSo ...

  3. Android OkHttp网络连接封装工具类

    package com.lidong.demo.utils; import android.os.Handler; import android.os.Looper; import com.googl ...

  4. java使用jsch连接linux

    由于项目需要使用java来linux进行管理,近一番查找,发现第三方jar包 jsch 可以轻松实现对linux的管理,(相关文档及例子请访问官网www.jcraft.com),故引进. 在网上搜索了 ...

  5. 基于JSch的Sftp工具类

    本Sftp工具类的API如下所示. 1)构造方法摘要 Sftp(String host, int port, int timeout, String username, String password ...

  6. jdbc连接的工具类

    在不实用框架的情况下,有一个jdbc的工具类来进行数据库的连接就再好不过了,下面提供这个工具类DBUtil.java package org.jdbc.test; import java.io.Inp ...

  7. C3P0连接池工具类使用

    c3p0的基本连接配置文件 c3p0-config.xml <c3p0-config> <default-config> <property name="dri ...

  8. C3P0连接池工具类实现步骤及方法

    C3P0连接池的工具类 使用C3P0获得连接对象连接池有一个规范接口 javax.sal.DataSourse 接口定义了一个从连接池中获得连接的方法getConnection(); 步骤导入jar包 ...

  9. JDBC连接Oracle工具类

    import java.sql.*;import java.util.ResourceBundle; /** * jdbc工具类,负责: * 1. 加载/注册数据库驱动程序 * 2. 获取数据库连接 ...

随机推荐

  1. linux切割文件【split命令详解】

    linux查看帮助 [tomcat-nohup]$ split --help 用法:split [选项]... [输入 [前缀]] 将输入内容拆分为固定大小的分片并输出到"前缀aa" ...

  2. unreal3控制台窗口属性调整

    在windows平台上,unreal3的console窗口类是FOutputDeviceConsoleWindows 启动时,它可以从XXXGame.ini中读取诸如窗口大小之类的属性,具体的代码在 ...

  3. 7、sraToolkit安装使用

    参考:http://blog.csdn.net/Cs_mary/article/details/78378552        ###prefetch 参数解释 https://www.ncbi.nl ...

  4. 15、Linux 文件属性和测试( chgrp,chown,chmod和-e -f -d -s

    一.更改文件属性 1.chgrp:更改文件属组 语法: chgrp [-R] 属组名文件名 参数选项 -R:递归更改文件属组,就是在更改某个目录文件的属组时,如果加上-R的参数,那么该目录下的所有文件 ...

  5. System.Threading.Thread的使用及传递参数等总结

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threa ...

  6. java知识点积累(一)

    知识点积累 1.关于final的重要知识点: final关键字可以用于成员变量.本地变量.方法以及类: final修饰的成员变量必须在声明时被初始化,或者在构造器中初始化,否则就会报编译错误: 不能够 ...

  7. CF622F The Sum of the k-th Powers(拉格朗日插值)

    题意 给出 \(n,k\) , \(n\le10^9,k\le10^6\) ,求 \(\sum_{i=1}^n i^k(mod\;10^9+7)\) 题解 自然数幂次和,是一个\(k+1\)次多项式, ...

  8. NSOperation的使用

    <iOS多线程编程之NSThread的使用> 介绍三种多线程编程和NSThread的使用,这篇介绍NSOperation的使用. 使用 NSOperation的方式有两种, 一种是用定义好 ...

  9. [SCOI2010]连续攻击游戏 BZOJ1854 二分图匹配

    题目描述 lxhgww最近迷上了一款游戏,在游戏里,他拥有很多的装备,每种装备都有2个属性,这些属性的值用[1,10000]之间的数表示.当他使用某种装备时,他只能使用该装备的某一个属性.并且每种装备 ...

  10. EIGRP-5-EIGRP数据包格式

    EIGRP数据包直接承戟在IP数据包中.协议号为88.EIGRP数据包的最大长度取决于具体接口上的最大IP MTU设置——通常完整IP数据包为1500字节.其中1480字节可以用于 EIGRP数据包. ...