java实现远程调用linux命令或脚本

1.xshell打开linux环境,创建一个测试脚本

#cd /opt

#mkdir zmy

# cd zmy

# vim test.sh

   键盘I键,进入编辑模式

  echo 'hello'

  echo $1

  键盘esc键,后输入:wq 保存退出

#cat test.sh

#ll(无执行权限)

#chmod +x test.sh

#ls -l

#测试脚本是否可执行

#./test.sh world  

#  sh ./test.sh world

输出 hello

        world

注:sh -x  ./test.sh world 

调试中可加入-x,可以看到执行过程

~~~~脚本创建成功!


给文件夹添加权限

chmod 755 -R filename

在linux终端先输入ll,可以看到如:
-rwx-r--r-- (一共10个参数) 表示文件所属组和用户的对应权限。
第一个跟参数属于管理员,跟chmod无关,先不管.
2-4参数:属于user
5-7参数:属于group
8-10参数:属于others
接下来就简单了:r==>可读 w==>可写 x==>可执行
r=4 w=2 x=1
所以755代表 rwxr-xr-x

777 代表 rwxr-rwx-rwx 所有用户都可读可写可执行。


2.编写java程序执行脚本

2.1gradle引入jar包

compile('org.jvnet.hudson:ganymed-ssh2:build210-hudson-1')
2.2

package com.xxx.travel.admin.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * Created by zhangmy on 2017/8/10.
 */
public class RemoteShellExecutor {
    private Connection conn;
    private String ipAddr;
    private Integer port;
    private String charset = Charset.defaultCharset().toString();
    private String userName;
    private String password;

    public RemoteShellExecutor(String ipAddr, Integer port, String userName, String password, String charset) {
        this.ipAddr = ipAddr;
        this.port = port;
        this.charset = charset;
        this.userName = userName;
        this.password = password;
    }

    /**
     * 登录远程服务器
     *
     * @return
     * @throws IOException
     */
    public boolean login() throws IOException {
        conn = new Connection(ipAddr, port);
        conn.connect();
        return conn.authenticateWithPassword(userName, password);
    }

    /**
     * 获取控制台输出信息
     *
     * @param inputStream
     * @param charset
     * @return
     */
    public String processStdout(InputStream inputStream, String charset) {
        InputStream in = new StreamGobbler(inputStream);
        StringBuffer stringBuffer = new StringBuffer();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, charset));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 主方法,调用执行命令
     *
     * @param cmds
     * @return
     */
    public String exec(String cmds) {
        InputStream inputStream = null;
        String result = "";
        Session session = null;
        try {
            if (this.login()) {
                session = conn.openSession();
                session.execCommand(cmds);
                inputStream = session.getStdout();
                //获取控制台标准输出
                result = this.processStdout(inputStream, this.charset);
                //如果输出为空,则说明执行失败,获取失败信息
                if (StringUtils.isBlank(result)) {
                    result = processStdout(session.getStderr(), this.charset);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (session != null) session.close();
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        RemoteShellExecutor executor = new RemoteShellExecutor
                ("192.168.1.200", 22, "root", "xxx", "utf-8");
        String result = executor.exec("sh -x /opt/zmy/test.sh 我是zmy");
        /*String result = executor.exec("cd /opt;pwd; ls -l");*/
        System.out.println(result);
    }


}


注:在java程序中如果想一次性连续执行多个命令,可用英文分号隔开多条命令。

参考:

http://blog.csdn.net/u013089991/article/details/52448989

http://blog.csdn.net/freedom2028/article/details/7104131

1.如果每个命令被一个分号 (;) 所分隔,那么命令会连续的执行下去,

2.如果每个命令被 && 号分隔,那么这些命令会一直执行下去,如果中间有错误的命令存在,则不再执行后面的命令,没错则执行到完为止,

3.如果每个命令被双竖线(||)分隔符分隔,如果命令遇到可以成功执行的命令,那么命令停止执行,即使后面还有正确的命令则后面的所有命令都将得不到执行。假如命令一开始就执行失败,那么就会执行 || 后的下一个命令,直到遇到有可以成功执行的命令为止,假如所有的都失败,则所有这些失败的命令都会被尝试执行一次


  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值