- 浏览: 379564 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (215)
- ubuntu (27)
- 虚拟机 (13)
- 数据库 (29)
- JAVA (40)
- 搜索 (23)
- 开发工具 (2)
- 产品 (2)
- 工具 (1)
- 应用服务器 (5)
- linux (17)
- log (1)
- 多线程 (3)
- 异常 (1)
- shell (6)
- 12306 ;互联网 (1)
- 持续集成&Hudson (4)
- js (1)
- JAVA OR-Map (1)
- 漏洞 (1)
- svn (1)
- MAVEN (3)
- 架构 (1)
- windows (1)
- json (1)
- web (3)
- jenkins (2)
- iptables (2)
- JAVA ssh (0)
- 项目管理 (1)
- tomcat (1)
- 安全 (1)
- 数据库 mysql (1)
- 性能 (1)
最新评论
-
sbwfgihc:
怎么用的啊,
<转>mysql 树查询语句 -
panghaoyu:
实现一个智能提示功能需要ajax、数据库、jsp/php、算法 ...
<转>Solr Suggest实现搜索智能提示 -
songsove:
请问您qq多少
solr 对拼音搜索和拼音首字母搜索的支持 -
panghaoyu:
实现一个智能提示功能需要ajax、数据库、jsp/php、算法 ...
<转>Solr Suggest实现搜索智能提示 -
norain1988:
这样就可以实现相关搜索了吗
solr 百度相关搜索类似功能的实现
原链:http://blog.csdn.net/hongbinchen/article/details/6567395
jsch 是纯java实现ssh功能,
下面是如何实现在远程机器上执行linux命令
摘自hadoop开源包的源码:
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.util;
import com.jcraft.jsch.*;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* Remote Execution of commands on a remote machine.
*/
public class SSHRemoteExecution implements RemoteExecution {
static final Log LOG = LogFactory.getLog(SSHRemoteExecution.class);
static final int SSH_PORT = 22;
static final String DEFAULT_IDENTITY="id_dsa";
static final String DEFAULT_KNOWNHOSTS="known_hosts";
static final String FS = System.getProperty("file.separator");
static final String LS = System.getProperty("line.separator");
private int exitCode;
private StringBuffer output;
private String commandString;
final StringBuffer errorMessage = new StringBuffer();
public SSHRemoteExecution() throws Exception {
}
protected String getHomeDir() {
String currentUser=System.getProperty("user.name");
String userHome=System.getProperty("user.home");
return userHome.substring(0, userHome.indexOf(currentUser)-1);
}
/**
* Execute command at remote host under given user
* @param remoteHostName remote host name
* @param user is the name of the user to be login under;
* current user will be used if this is set to <code>null</code>
* @param command to be executed remotely
* @param identityFile is the name of alternative identity file; default
* is ~user/.ssh/id_dsa
* @param portNumber remote SSH daemon port number, default is 22
* @throws Exception in case of errors
*/
public void executeCommand (String remoteHostName, String user,
String command, String identityFile, int portNumber) throws Exception {
commandString = command;
String sessionUser = System.getProperty("user.name");
String userHome=System.getProperty("user.home");
if (user != null) {
sessionUser = user;
userHome = getHomeDir() + FS + user;
}
String dotSSHDir = userHome + FS + ".ssh";
String sessionIdentity = dotSSHDir + FS + DEFAULT_IDENTITY;
if (identityFile != null) {
sessionIdentity = identityFile;
}
JSch jsch = new JSch();
Session session = jsch.getSession(sessionUser, remoteHostName, portNumber);
jsch.setKnownHosts(dotSSHDir + FS + DEFAULT_KNOWNHOSTS);
jsch.addIdentity(sessionIdentity);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(30000); // making a connection with timeout.
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
final BufferedReader errReader =
new BufferedReader(
new InputStreamReader(((ChannelExec)channel).getErrStream()));
BufferedReader inReader =
new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.connect();
Thread errorThread = new Thread() {
@Override
public void run() {
try {
String line = errReader.readLine();
while((line != null) && !isInterrupted()) {
errorMessage.append(line);
errorMessage.append(LS);
line = errReader.readLine();
}
} catch(IOException ioe) {
LOG.warn("Error reading the error stream", ioe);
}
}
};
try {
errorThread.start();
} catch (IllegalStateException e) {
LOG.debug(e);
}
try {
parseExecResult(inReader);
String line = inReader.readLine();
while (line != null) {
line = inReader.readLine();
}
if(channel.isClosed()) {
exitCode = channel.getExitStatus();
LOG.debug("exit-status: " + exitCode);
}
try {
// make sure that the error thread exits
errorThread.join();
} catch (InterruptedException ie) {
LOG.warn("Interrupted while reading the error stream", ie);
}
} catch (Exception ie) {
throw new IOException(ie.toString());
}
finally {
try {
inReader.close();
} catch (IOException ioe) {
LOG.warn("Error while closing the input stream", ioe);
}
try {
errReader.close();
} catch (IOException ioe) {
LOG.warn("Error while closing the error stream", ioe);
}
channel.disconnect();
session.disconnect();
}
}
/**
* Execute command at remote host under given username
* Default identity is ~/.ssh/id_dsa key will be used
* Default known_hosts file is ~/.ssh/known_hosts will be used
* @param remoteHostName remote host name
* @param user is the name of the user to be login under;
* if equals to <code>null</code> then current user name will be used
* @param command to be executed remotely
*/
@Override
public void executeCommand (String remoteHostName, String user,
String command) throws Exception {
executeCommand(remoteHostName, user, command, null, SSH_PORT);
}
@Override
public int getExitCode() {
return exitCode;
}
protected void parseExecResult(BufferedReader lines) throws IOException {
output = new StringBuffer();
char[] buf = new char[512];
int nRead;
while ( (nRead = lines.read(buf, 0, buf.length)) > 0 ) {
output.append(buf, 0, nRead);
}
}
/** Get the output of the ssh command.*/
@Override
public String getOutput() {
return (output == null) ? "" : output.toString();
}
/** Get the String representation of ssh command */
@Override
public String getCommandString() {
return commandString;
}
}
jsch 是纯java实现ssh功能,
下面是如何实现在远程机器上执行linux命令
摘自hadoop开源包的源码:
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.util;
import com.jcraft.jsch.*;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* Remote Execution of commands on a remote machine.
*/
public class SSHRemoteExecution implements RemoteExecution {
static final Log LOG = LogFactory.getLog(SSHRemoteExecution.class);
static final int SSH_PORT = 22;
static final String DEFAULT_IDENTITY="id_dsa";
static final String DEFAULT_KNOWNHOSTS="known_hosts";
static final String FS = System.getProperty("file.separator");
static final String LS = System.getProperty("line.separator");
private int exitCode;
private StringBuffer output;
private String commandString;
final StringBuffer errorMessage = new StringBuffer();
public SSHRemoteExecution() throws Exception {
}
protected String getHomeDir() {
String currentUser=System.getProperty("user.name");
String userHome=System.getProperty("user.home");
return userHome.substring(0, userHome.indexOf(currentUser)-1);
}
/**
* Execute command at remote host under given user
* @param remoteHostName remote host name
* @param user is the name of the user to be login under;
* current user will be used if this is set to <code>null</code>
* @param command to be executed remotely
* @param identityFile is the name of alternative identity file; default
* is ~user/.ssh/id_dsa
* @param portNumber remote SSH daemon port number, default is 22
* @throws Exception in case of errors
*/
public void executeCommand (String remoteHostName, String user,
String command, String identityFile, int portNumber) throws Exception {
commandString = command;
String sessionUser = System.getProperty("user.name");
String userHome=System.getProperty("user.home");
if (user != null) {
sessionUser = user;
userHome = getHomeDir() + FS + user;
}
String dotSSHDir = userHome + FS + ".ssh";
String sessionIdentity = dotSSHDir + FS + DEFAULT_IDENTITY;
if (identityFile != null) {
sessionIdentity = identityFile;
}
JSch jsch = new JSch();
Session session = jsch.getSession(sessionUser, remoteHostName, portNumber);
jsch.setKnownHosts(dotSSHDir + FS + DEFAULT_KNOWNHOSTS);
jsch.addIdentity(sessionIdentity);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(30000); // making a connection with timeout.
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
final BufferedReader errReader =
new BufferedReader(
new InputStreamReader(((ChannelExec)channel).getErrStream()));
BufferedReader inReader =
new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.connect();
Thread errorThread = new Thread() {
@Override
public void run() {
try {
String line = errReader.readLine();
while((line != null) && !isInterrupted()) {
errorMessage.append(line);
errorMessage.append(LS);
line = errReader.readLine();
}
} catch(IOException ioe) {
LOG.warn("Error reading the error stream", ioe);
}
}
};
try {
errorThread.start();
} catch (IllegalStateException e) {
LOG.debug(e);
}
try {
parseExecResult(inReader);
String line = inReader.readLine();
while (line != null) {
line = inReader.readLine();
}
if(channel.isClosed()) {
exitCode = channel.getExitStatus();
LOG.debug("exit-status: " + exitCode);
}
try {
// make sure that the error thread exits
errorThread.join();
} catch (InterruptedException ie) {
LOG.warn("Interrupted while reading the error stream", ie);
}
} catch (Exception ie) {
throw new IOException(ie.toString());
}
finally {
try {
inReader.close();
} catch (IOException ioe) {
LOG.warn("Error while closing the input stream", ioe);
}
try {
errReader.close();
} catch (IOException ioe) {
LOG.warn("Error while closing the error stream", ioe);
}
channel.disconnect();
session.disconnect();
}
}
/**
* Execute command at remote host under given username
* Default identity is ~/.ssh/id_dsa key will be used
* Default known_hosts file is ~/.ssh/known_hosts will be used
* @param remoteHostName remote host name
* @param user is the name of the user to be login under;
* if equals to <code>null</code> then current user name will be used
* @param command to be executed remotely
*/
@Override
public void executeCommand (String remoteHostName, String user,
String command) throws Exception {
executeCommand(remoteHostName, user, command, null, SSH_PORT);
}
@Override
public int getExitCode() {
return exitCode;
}
protected void parseExecResult(BufferedReader lines) throws IOException {
output = new StringBuffer();
char[] buf = new char[512];
int nRead;
while ( (nRead = lines.read(buf, 0, buf.length)) > 0 ) {
output.append(buf, 0, nRead);
}
}
/** Get the output of the ssh command.*/
@Override
public String getOutput() {
return (output == null) ? "" : output.toString();
}
/** Get the String representation of ssh command */
@Override
public String getCommandString() {
return commandString;
}
}
发表评论
-
<转>Hessian入门(与Spring集成)
2015-01-20 10:31 4357原链接:http://blog.csdn.net/chenwe ... -
<转>如何编程实现 2 + 2 = 5?
2014-10-16 11:00 768原链接:http://codeway.co/%E5%A6%82 ... -
<转>利用位操作来进行状态操作
2014-07-15 11:00 663print?<SPAN style="BACK ... -
java命令
2014-04-23 17:17 773jps -v 查看所有的jvm进程,包括进程ID,进程启动的路 ... -
<转>给Tomcat,Apache配置gzip压缩(HTTP压缩)功能
2014-03-28 14:14 415原链接:http://www.blogjava.net/juh ... -
shell要注意空格
2014-02-26 18:08 731syntax error near unexpected to ... -
<转>JVM调优总结 -Xms -Xmx -Xmn -Xss
2014-01-21 21:21 833原链接:http://unixboy.iteye.com/bl ... -
1>/dev/null 2>&1的含义
2014-01-21 10:53 750hell中可能经常能看到:>/dev/null 2> ... -
<转>linux test命令详解
2014-01-21 10:41 789原链接: http://hi.baidu.com/w23410 ... -
shell学习
2014-01-13 15:07 467http://bbs.chinaunix.net/forum. ... -
<转>Eclipse 常用设置
2013-12-23 16:26 667原链:http://blog.csdn.net/appleca ... -
tomcat各版本信息
2013-12-23 10:02 751Apache官方对各版本的解释:http://tomcat ... -
<转> 如何获取用户的真实IP
2013-12-23 09:40 651问题引出: 在JSP里,获取客户端的IP地址的方法是:re ... -
从SVN导出指定版本号之间修改的文件
2013-12-20 16:55 515转:http://www.kuqin.com/manageto ... -
用JAVA调用ssh命令
2013-12-09 15:21 1886原链:http://blog.csdn.net/f ... -
java执行shell命令 outputStream缓冲区阻塞
2013-11-27 15:49 1691http://bbs.csdn.net/topics/1101 ... -
java有效的IP正则表达式
2013-11-06 20:46 820public static boolean isboolIp ... -
<转>session 之session混乱解决方法
2013-08-07 21:23 1731转:http://blog.csdn.net/wmj2003/ ... -
Java JSON技术框架选型与实例
2013-08-05 15:12 762JSON JSON英文全称为JavaScript Obje ... -
JVM内存结构系列:HotSpot内存结构最清晰
2013-07-29 11:37 760SUN的jvm内存池被划分为以下几个部分:Eden Spa ...
相关推荐
主要介绍了Java中通过jsch来连接远程服务器执行linux命令的相关资料,需要的朋友可以参考下
jsch,jsch工具类,jsch实现远程sftp,jsch实现过程 通过JSch实现sftp传输文件
jsch通过java代码ssh登录主机远程执行命令并返回结果。注意,这个是源代码,请自行编译后在使用。当然,也可以根据自己的需要更改源代码。
参考expect4j的交互式操作方式控制输入输出流实现批量执行多条shell命令同时支持切换用户输入密码提权执行命令输入密码等操作 有完整的测试用例,便于理解 模板化执行命令示例 [$]send[su - root] [Password:]...
适用多线程的SFTP类,支持代理服务器,是spring服务类,无需修改可直接与spring结合使用。 代码经过大量的并发使用验证,稳定... <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
jsch 连接 sftp进行简单操作的工具类 pom <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.53</version> </dependency>
是使用java使用JSCH进行连接远程服务器的Demo,让更多刚刚接触的同学进行学习。
软件开发与测试人员常常会在远程 Linux/UNIX 系统上执行命令或脚本,有时还会有批量执行任务的需求。常见的办法是通过本地工具(例如 Putty)连接远程计算机,输入命令执行,但是当遇到需要集成这些任务到代码或者...
最新jsch.jar,通过该包可实现ant控制linux操作,如启动服务器、scp命令等
http://blog.csdn.net/clariones/article/details/8455345
这里是我使用jsch连接linux并且执行相关命令的案例,希望对你有所帮助。
纯java实现的ssh协议(jsch),支持同时连接多台linux主机,执行相同的命令。只需配置目标主机的ip地址、用户名和密码即可实现远程操作。服务器无需配置ssh对等协议或安装任何agent插件。并发远程主机主机连接,顺序...
jsch实现sftp文件上传、下载文件,提供jsch jar
jsch-0.1.53.jar,实现SFTP上传下载删除,ava中通过jsch来连接远程服务器执行linux命令
jsch.jar java通过代码登录远程linux服务器并执行linux命令需要的jar包
主要介绍了如何用java程序(JSch)运行远程linux主机上的shell脚本,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
基于jsch包实现远程服务器的sftp访问,并可远程发送命令执行,可以配合https://download.csdn.net/download/u011230766/10710755,实现密钥登录,类KeyGen用于生成非对称密钥
JSch对linux上文件的上传,下载,批量处理,删除文件等等,已在项目中使用。
*我写的一段小程序,实现的主要功能是同步sftp上的文件夹(sftp->本地) *我写的一个小程序,用于将字符串转化成其他编码格式。如果乱码问题依然没解决,这个类也许能帮你找到你需要更改的编码类型。然后修改那三处...
本地cmd命令, 输入命令, 并在控制台输出命令执行结果 jsch 远程ssh到linux服务器, 执行结果并显示输出