JSch 介绍

JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器

1.导入jar包

<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.</version>
</dependency>

2.JAVA程序连接SSH实例

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList; import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo; /**
*
* @desc SSHConnectionTest.java
*
* @author xianlei
* @date 2018年3月29日下午5:53:24
*/
public class SSHConnectionTest {
//远程主机的ip地址
private String ip;
//远程主机登录用户名
private String username;
//远程主机的登录密码
private String password;
//设置ssh连接的远程端口
public static final int DEFAULT_SSH_PORT = 22;
//保存输出内容的容器
private ArrayList<String> stdout; class MyUserInfo implements UserInfo { @Override
public String getPassphrase() {
// TODO Auto-generated method stub
System.out.println("MyUserInfo.getPassphrase()");
return null;
} @Override
public String getPassword() {
// TODO Auto-generated method stub
System.out.println("MyUserInfo.getPassword()");
return null;
} @Override
public boolean promptPassphrase(String arg0) {
// TODO Auto-generated method stub
System.out.println("MyUserInfo.promptPassphrase()");
System.out.println(arg0);
return false;
} @Override
public boolean promptPassword(String arg0) {
// TODO Auto-generated method stub
System.out.println("MyUserInfo.promptPassword()");
System.out.println(arg0);
return false;
} @Override
public boolean promptYesNo(String arg0) {
// TODO Auto-generated method stub'
System.out.println("MyUserInfo.promptYesNo()");
System.out.println(arg0);
if (arg0.contains("The authenticity of host")) {
return true;
}
return true;
} @Override
public void showMessage(String arg0) {
// TODO Auto-generated method stub
System.out.println("MyUserInfo.showMessage()");
} } /**
* 初始化登录信息
* @param ip
* @param username
* @param password
*/
public SSHConnectionTest(final String ip, final String username, final String password) {
this.ip = ip;
this.username = username;
this.password = password;
stdout = new ArrayList<String>();
}
/**
* 执行shell命令
* @param command
* @return
*/
public int execute(final String command) {
int returnCode = 0;
JSch jsch = new JSch();
MyUserInfo userInfo = new MyUserInfo(); try {
//创建session并且打开连接,因为创建session之后要主动打开连接
Session session = jsch.getSession(username, ip, DEFAULT_SSH_PORT);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.setUserInfo(userInfo);
session.connect(); //打开通道,设置通道类型,和执行的命令
Channel channel = session.openChannel("exec");
ChannelExec channelExec = (ChannelExec)channel;
channelExec.setCommand(command); channelExec.setInputStream(null);
BufferedReader input = new BufferedReader(new InputStreamReader
(channelExec.getInputStream())); channelExec.connect();
System.out.println("The remote command is :" + command); //接收远程服务器执行命令的结果
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
}
input.close(); // 得到returnCode
if (channelExec.isClosed()) {
returnCode = channelExec.getExitStatus();
} // 关闭通道
channelExec.disconnect();
//关闭session
session.disconnect(); } catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return returnCode;
}
/**
* get stdout
* @return
*/
public ArrayList<String> getStandardOutput() {
return stdout;
} public static void main(final String [] args) {
String password = "";
String username = "root";
String ip = "";
SSHConnectionTest shell = new SSHConnectionTest(ip, username, password); //启动redis服务命令
shell.execute("cd /usr/local/redis && ./redis-server redis.conf &");
//关闭redis服务命令
// shell.execute("cd /usr/local/redis && ./redis-cli shutdown"); ArrayList<String> stdout = shell.getStandardOutput();
for (String str : stdout) {
System.out.println(str);
}
}
}

java程序连接Liunx服务器并且执行命令的更多相关文章

  1. java连接远程服务器并执行命令

    导入必要的jar包 <dependency>  <groupId>ch.ethz.ganymed</groupId> <artifactId>ganym ...

  2. java ssh远程服务器并执行多条shell命令

    java ssh远程服务器并执行多条命令 import java.io.BufferedReader; import java.io.IOException; import java.io.Input ...

  3. 【Shell实战】批量在多台服务器上执行命令

    功能说明:批量在多台服务器上执行命令 #!/bin/bash # ========================================== # 功能:批量在多台服务器上执行命令 # 方法: ...

  4. Python 实现远程服务器批量执行命令

    paramiko 远程控制介绍 Python paramiko是一个相当好用的远程登录模块,采用ssh协议,可以实现linux服务器的ssh远程登录.首先来看一个简单的例子 import parami ...

  5. Python通过ssh连接服务器并执行命令

    [本文出自天外归云的博客园] 脚本示例如下: # coding:utf-8 import time,paramiko,re,StringIO def exec_shell(command): ''' ...

  6. linux下远程服务器批量执行命令及SFTP上传文件 -- python实现

    之前写过一个python远程执行命令的脚本,但在一个性能测试中,要将程序批量分发到不同服务器,程序无法使用,再将之前的脚本更新,加入批量上传的功能.之前脚本地址:http://www.cnblogs. ...

  7. ssh远程连接linux服务器并执行命令

    详细方法: SSHClient中的方法 参数和参数说明 connect(实现ssh连接和校验) hostname:目标主机地址 port:主机端口 username:校验的用户名 password:登 ...

  8. Java远程连接Linux服务器并执行命令及上传文件

    最近再开发中遇到需要将文件上传到Linux服务器上,至此整理代码笔记. 此种连接方法中有考虑到并发问题,在进行创建FTP连接的时候将每一个连接对象存放至 ThreadLocal<Ftp> ...

  9. golang使用ssh远程连接服务器并执行命令

    安装golang.org/x 直接去github上面,把https://github.com/zieckey/golang.org,把整个目录拷贝下来放到你的gopath下面即可.记住在gopath的 ...

随机推荐

  1. sql中级语句

    创建联结 select n_title,n_content,t_name,t_memo from nrc_news,nrc_type where nrc_news.t_id=nrc_type.t_id ...

  2. springBoot整合Listener

    新建项目 这个是pom文件 <properties> <java.version>1.8</java.version> </properties> &l ...

  3. 解决Win7上的连接access数据库的问题

    最近做了一个win桌面程序,没有用sql 数据库,而是用access数据库,因为access比sql用起来方便多了,最主要是不要安装sql server,直接放在程序里面,然后创建连接字符就可以了,s ...

  4. csp模拟赛低级错误及反思

    \(csp\)模拟赛低级错误及反思. 1.没开\(longlong\). 反思:注意数据类型以及数据范围. 2.数组越界(前向星数组未开两倍,一题的数据范围应用到另一题上,要开两倍的写法为开两倍数组) ...

  5. 学习 Laravel - Web 开发实战入门笔记(1)

    本笔记根据 LearnKu 教程边学边记而成.该教程以搭建出一个类似微博的Web 应用为最终成果,在过程中学习 Laravel 的相关知识. 准备开发环境 原教程使用官方推荐的 Homestead 开 ...

  6. 刨根究底字符编码之十——Unicode字符集的编码方式以及码点、码元

    Unicode字符集的编码方式以及码点.码元 一.字符编码方式CEF的选择 1. 由于Unicode字符集非常大,有些字符的编号(码点值)需要两个或两个以上字节来表示,而要对这样的编号进行编码,也必须 ...

  7. Scala学习四——映射和数组

    一.本章要点 Scala有十分易用的语言来创建,查询和遍历映射 你需要从可变和不可变的映射中做出选择 默认情况下,你得到的是一个哈希映射,不过你也可以指明要树形映射 你可以很容易地在Scala映射和J ...

  8. 【原创】Linux基础之去掉windows中的\r

    linux换行为\n,windows换行为\r\n,windows环境编辑的shell脚本在linux下执行会报错: line 2: $'\r': command not found 查看 # cat ...

  9. global.css

    global.css /* 页面元素初始化和常用样式定义-start */ /*======== 全局 ========*/ body, div, dl, dt, dd, ul, ol, li, h1 ...

  10. 409 Conflict - PUT https://registry.npm.taobao.org/-/user/org.couchdb.user:zphtown - [conflict] User xxx already exists

    解决方法cmd执行 npm config set registry https://registry.npmjs.org/ 为什么,参考此文档:https://blog.csdn.net/adc_go ...