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登录
将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 “自动下载并打包完毕”