java连接linux并且执行shell脚本

java连接shell脚本

一:linux系统准备

  • 下载wget更换yum源

    yum -y install wget
    
  • 更换阿里yum源

    wget -O CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    
  • 下载tree maven git

    yum -y install tree
    yum -y install maven
    yum -y install git
    
  • 准备SSH远程连接环境

    安装ssh环境

    yum -y install openssh-server
    

    编辑配置文件

    vim /etc/ssh/sshd_config
    打开22端口号
    使用root登录
    

a29p2q.png
a2pzPs.png

将sshd服务添加到自启动列表

systemctl enable sshd_service

java连接linux系统

  • 依赖导入

       <groupId>ch.ethz.ganymed</groupId>
                <artifactId>ganymed-ssh2</artifactId>
                <version>build210</version>
    
  • api使用

     // 通过SSH2协议远程与linux建立连接
            Connection con = new Connection("192.168.23.129",22);
            Session session=null;
            //建立连接
            con.connect();
            //登录系统
            boolean b = con.authenticateWithPassword("root", "root");
            if(b){
                // 获得连接
                 session = con.openSession();
                // 执行脚本
                session.execCommand("bash /jva_01.sh "+repositoryPath+name);
                StreamGobbler gobbler = new StreamGobbler(session.getStdout());
                BufferedReader reader = new BufferedReader(new InputStreamReader(gobbler));
                // 获得脚本执行的结果
                Stream<String> lines = reader.lines();
                lines.forEach(s-> System.out.println(s));
                // 0成功 非0失败
                System.out.println("运行结果:"+session.getExitStatus());
                session.close();
                con.close();
            }else {
                // 连接失败
                System.out.println("与服务器连接失败");
            }
        }
    
  • shell脚本准备

    :<<!
    第一个bash脚本自动获取git仓库
    并且克隆到本地
    !
    
    filePath=$1
    
    directoryName=$2
    
    
    test(){
    
    # 创建仓库
    
    
    mk="mkdir ${directoryName} "
    
    
    # 切换目录
    qihuan="cd /${directoryName}"
    # 初始化仓库
    init="git init"
    # 从远程仓库拉取大妈
    
    clone="git clone ${filePath} "
    
    
    # 使用maven打包
    mvn="mvn package"
    
    # 执行命令
    
    ${mk}
    
    ${qihuan}
    
    ${init}
    
    ${clone}
    
    
    ${mvn}
    
    }
    
    # 调用函数
    
    test
    
    echo "自动下载并打包完毕"
    
    

    ${mk}

    ${qihuan}

    ${init}

    ${clone}

    ${mvn}

    }

    调用函数

    test

    echo “自动下载并打包完毕”

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值