在linux的脚本中,如果不对机器做其他的处理,不能实现在linux的机器上执行命令。为了解决这个问题,写了个小工具来解决这个问题。

后面的代码是利用java实现的可远程执行linux命令的小工具,代码中使用了jsch这个开源包。

JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。jsch的jar,可从官网下载。

 import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; 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; /**
*
* 类似ssh执行命令的小工具
*
* @author walker
*
*/
public class SSH {
private String userName;
private String password;
private String host; public SSH(String host, String userName, String password) {
this.host = host;
this.userName = userName;
this.password = password;
} private Session getSession() {
JSch jsch = new JSch();
Session session = null; try {
session = jsch.getSession(userName, host);
session.setPassword(password); Properties props = new Properties();
props.put("StrictHostKeyChecking", "no");
session.setConfig(props);
session.connect();
} catch (JSchException e) {
e.printStackTrace();
}
return session;
} public boolean exec(String[] cmds) {
StringBuffer cmdBuffer = new StringBuffer(); for (int i = 0; i < cmds.length; i++) {
if (i != 3) {
cmdBuffer.append(" ");
}
cmdBuffer.append(cmds[i]);
}
return exec(cmdBuffer.toString());
} public boolean exec(String cmd) {
Session session = getSession();
Channel channel = null;
InputStream in = null;
try {
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(cmd);
((ChannelExec) channel).setInputStream(null);
((ChannelExec) channel).setErrStream(System.err); // 获取执行错误的信息 in = channel.getInputStream();
channel.connect();
byte[] b = new byte[1024];
int size = -1;
while ((size = in.read()) > -1) {
System.out.print(new String(b, 0, size)); // 打印执行命令的所返回的信息
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
// 关闭连接
channel.disconnect();
session.disconnect();
} return false;
} /**
* @param args
*/
public static void main(String[] args) {
if (args.length < 4) {
System.err.println("usage:\n\t" + SSH.class.getName()
+ " <host> <usename> <password> <cmds>");
System.exit(1);
} // 用以保存命令(可能是一串很长的命令)
StringBuffer cmdBuffer = new StringBuffer();
for (int i = 3; i < args.length; i++) {
if (i != 3) {
cmdBuffer.append(" ");
}
cmdBuffer.append(args[i]);
} SSH ssh = new SSH(args[0], args[1], args[2]);
System.exit(ssh.exec(cmdBuffer.toString()) ? 0 : 1);
}
}

利用java实现可远程执行linux命令的小工具的更多相关文章

  1. java中使用Process执行linux命令

    代码如下 BufferedReader reader = null; String cmd = "netstat -anp|grep :8080";//命令中有管道符 | 需要如下 ...

  2. 基于paramiko进行远程执行Linux命令

    直接贴一段代码import paramiko class remote_start(object): def __init__(self,host,username,pwd): self.ssh = ...

  3. Java程序执行Linux命令

    Java程序中要执行linux命令主要依赖2个类:Process和Runtime 首先看一下Process类: ProcessBuilder.start() 和 Runtime.exec 方法创建一个 ...

  4. Java程序执行Linux命令(JSP运行其他程序)

    java程序中要执行linux命令主要依赖2个类:Process和Runtime 首先看一下Process类: ProcessBuilder.start() 和 Runtime.exec 方法创建一个 ...

  5. Java 执行linux命令(转)

    转自 http://blog.csdn.net/a19881029/article/details/8063758 java程序中要执行linux命令主要依赖2个类:Process和Runtime 首 ...

  6. Pyhton 利用threading远程下发文件和远程执行linux系统命令

    #!/usr/bin/env python # encoding: utf-8 #__author__ = 'cp' #__date__ = '21/07/16 上午 10:32' import th ...

  7. Linux远程执行shell命令

    Linux远程执行shell命令   在Linux系统中,我们经常想在A机器上,执行B机器上的SHELL命令. 下面这种方案,是一种流行可靠的方案. 1.SSH无密码登录 # 本地服务器执行(A机器) ...

  8. 再见Xshell、Xftp!Python执行Linux命令、上传下载远程文件

    相信大家应该都接触过Linux操作系统(Ubuntu.Centos等),那么在使用的Linux操作系统需要使用一些远程ssh工具,尤其是公网服务器. 常用的ssh工具主要有:Xshell.MobaXt ...

  9. Linux远程执行Shell命令或脚本

    ## 远程执行shell命令 ssh [user]@[server] '[command]' # eg. ssh root@192.168.1.1 'uptime' ## 远程执行本地shell脚本 ...

随机推荐

  1. POJ2251-Dungeon Master(3维BFS)

    You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of un ...

  2. 【LeetCode算法题库】Day5:Roman to Integer & Longest Common Prefix & 3Sum

    [Q13] Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Valu ...

  3. 前端常见算法面试题之 - 重建二叉树[JavaScript解法]

    题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列[1,2,4,7,3,5,6,8],和中序遍历序列[4,7 ...

  4. uiimageview 的 animation 动画

    NSMutableArray *meiArr = [NSMutableArray arrayWithCapacity:4]; for (int i = 0; i < 4; i++) { NSSt ...

  5. virtual box下安装ubuntu经验

    1. 哪怕下载的是ubuntu64位版本,也在vitualbox下选择ubuntu而不要选择ubuntu(64bit) 2. 安装VBoxGuestAdditional.iso:下载和vbox版本相匹 ...

  6. 移动设备检测类Mobile_Detect.php

    移动设备检测类Mobile_Detect.php http://mobiledetect.net/ 分类:PHP 时间:2015年11月28日 Mobile_Detect.php是一个轻量级的开源移动 ...

  7. map的运用

    一.map是一种关联容器,支持高效的查找和访问 map中的元素是一些关键字-值(key-value)对: 关键字起索引作用: 值表示与索引相关联的数据. 关联容器中元素是根据关键字存储的,故其不支持位 ...

  8. 王者荣耀交流协会PSP Daily项目Postmortem结果

    王者荣耀交流协会PSP Daily项目Postmortem结果 整理:王超 设想和目标 1.       我们的软件要解决什么问题?是否定义得很清楚?是否对典型用户和典型场景有清晰的描述? PSP D ...

  9. Daily Scrum10 11.14

    昨天的任务已经完成,但是我们在完成任务的过程中确实遇到了困难.昨天我们发现无法连接sqlserver的时候,给罗杰老师发了邮件.老师也给我们提出了建议,给我们提供了一些参考.所以今天大家都在研究如何解 ...

  10. jquery前端第一讲

    1.bootstrap里面的文件是什么意思: bootstrap.cssbootstrap.min.cssbootstrap-responsive.cssbootstrap-responsive.mi ...