- 浏览: 389628 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (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 4431原链接:http://blog.csdn.net/chenwe ... -
<转>如何编程实现 2 + 2 = 5?
2014-10-16 11:00 828原链接:http://codeway.co/%E5%A6%82 ... -
<转>利用位操作来进行状态操作
2014-07-15 11:00 708print?<SPAN style="BACK ... -
java命令
2014-04-23 17:17 822jps -v 查看所有的jvm进程,包括进程ID,进程启动的路 ... -
<转>给Tomcat,Apache配置gzip压缩(HTTP压缩)功能
2014-03-28 14:14 451原链接:http://www.blogjava.net/juh ... -
shell要注意空格
2014-02-26 18:08 809syntax error near unexpected to ... -
<转>JVM调优总结 -Xms -Xmx -Xmn -Xss
2014-01-21 21:21 881原链接:http://unixboy.iteye.com/bl ... -
1>/dev/null 2>&1的含义
2014-01-21 10:53 789hell中可能经常能看到:>/dev/null 2> ... -
<转>linux test命令详解
2014-01-21 10:41 827原链接: http://hi.baidu.com/w23410 ... -
shell学习
2014-01-13 15:07 508http://bbs.chinaunix.net/forum. ... -
<转>Eclipse 常用设置
2013-12-23 16:26 712原链:http://blog.csdn.net/appleca ... -
tomcat各版本信息
2013-12-23 10:02 835Apache官方对各版本的解释:http://tomcat ... -
<转> 如何获取用户的真实IP
2013-12-23 09:40 698问题引出: 在JSP里,获取客户端的IP地址的方法是:re ... -
从SVN导出指定版本号之间修改的文件
2013-12-20 16:55 558转:http://www.kuqin.com/manageto ... -
用JAVA调用ssh命令
2013-12-09 15:21 1945原链:http://blog.csdn.net/f ... -
java执行shell命令 outputStream缓冲区阻塞
2013-11-27 15:49 1734http://bbs.csdn.net/topics/1101 ... -
java有效的IP正则表达式
2013-11-06 20:46 865public static boolean isboolIp ... -
<转>session 之session混乱解决方法
2013-08-07 21:23 1774转:http://blog.csdn.net/wmj2003/ ... -
Java JSON技术框架选型与实例
2013-08-05 15:12 803JSON JSON英文全称为JavaScript Obje ... -
JVM内存结构系列:HotSpot内存结构最清晰
2013-07-29 11:37 806SUN的jvm内存池被划分为以下几个部分:Eden Spa ...
相关推荐
本文将详细介绍如何使用JSCH库在Java中连接远程服务器并执行Linux命令。 首先,我们需要导入JSCH库。如果你使用的是Maven项目,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.jcraft</...
一旦连接建立成功,我们可以使用`session`对象的`execCommand()`方法执行Linux命令,比如`cp`或`rsync`进行文件拷贝。例如: ```java Channel channel = session.openChannel("exec"); ((ChannelExec) channel)....
标题中的“通过SSHPASS执行命令及相关脚本”是指在Linux环境下使用`sshpass`工具进行非交互式SSH登录并执行远程命令的技术。`sshpass`是一个命令行实用程序,它允许用户在不手动输入密码的情况下,通过SSH连接执行...
例如,要在本地监听31521端口,并将其转发到跳板机上的172.18.129.13主机的1521端口,可以执行以下命令: ```bash ssh -L 31521:172.18.129.13:1521 bea@124.225.110.4 ``` 类似地,如果要访问跳板机后的其他服务...
远程调试是指在一台机器上运行Java应用程序,并允许另一台机器上的IDE连接到该应用程序进行调试的过程。 ##### 3.1 配置应用程序 - **启动诊断工具**:在Linux服务器上,通过Xshell或其他SSH客户端,使用以下命令...
SSH(Secure Shell)是一种网络协议,用于在不安全的网络上提供安全的远程登录和其他服务。在Java开发中,SSH通常指的是Spring、Struts和Hibernate这三个开源框架的组合,它们一起构建了强大的企业级应用开发基础。...
实现Linux远程连接windows并执行一些命令 ExtendDatabase 提高效率工具工程,扩展 ASE 数据库的data空间和log空间(默认增加 40G data和 10G log)。 DBLogMonitor 监控远程机器的数据库log文件,当日志已满时清空 ...
在IT行业中,SSH(Secure Shell)是一种网络协议,用于在不安全的网络上提供安全的远程登录和其他服务。SSH主要用于加密网络通信,确保数据传输过程中的安全性,防止中间人攻击和窃听。对于Java初级工程师而言,理解...
gossh用于管理linux(如unix)计算机:包括命令和推和拉文件的远程执行,并支持独立和批处理模式。 2,高斯能做什么 高斯的三个核心功能: 连接到远程主机以执行命令。 将本地文件或文件夹推送到远程主机。 将...
例如,可以使用JSch库来在Java程序中集成SSH功能,执行远程命令、传输文件等。JSch是一个纯Java实现的SSH2库,能够连接到SSH服务器,执行shell命令,实现SFTP(SSH文件传输协议)。 综上所述,SSH Shell服务在远程...