当前位置: 首页 > 工具软件 > jail-shell > 使用案例 >

java调用shell多线程_java调用shell脚本

长孙瑞
2023-12-01

## 调用mysql备份脚本

1. java调用Linux命令

~~~

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class RunShell {

public int runShell(String[] args) throws IOException, InterruptedException {

int exitValue = 0; //脚本执行返回状态码

InputStreamReader stdISR = null; // 标准输入流

InputStreamReader errISR = null; // error流

Process process = null;

String command = "";

for (String cmd : args) {

command += cmd + " ";

}

try {

process = Runtime.getRuntime().exec(command.trim());

exitValue = process.waitFor();

String line = null;

stdISR = new InputStreamReader(process.getInputStream());

BufferedReader stdBR = new BufferedReader(stdISR);

while ((line = stdBR.readLine()) != null) {

System.out.println("INFO line:" + line);

}

errISR = new InputStreamReader(process.getErrorStream());

BufferedReader errBR = new BufferedReader(errISR);

while ((line = errBR.readLine()) != null) {

System.out.println("ERROR line:" + line);

}

} finally {

try {

if (stdISR != null) {

stdISR.close();

}

if (errISR != null) {

errISR.close();

}

if (process != null) {

process.destroy();

}

} catch (IOException e) {

System.out.println("正式执行命令:" + command + "有IO异常");

}

}

return exitValue;

}

}

~~~

2. 测试类

~~~

import java.io.IOException;

/**

* Created by dailin on 2017/12/25.

*/

public class TestShell {

public static void main(String[] args) throws IOException, InterruptedException {

RunShell runShell = new RunShell();

int code = runShell.runShell(args);

System.out.println("执行状态:" + code);

}

}

~~~

3. 打包到Linux上

maven

加入打包插件

~~~

App

maven-assembly-plugin

false

jar-with-dependencies

JavaTest.shell.TestShell

make-assembly

package

assembly

~~~

4. shell脚本

~~~

#!/bin/bash

#set -x

source $1

DATE=`date +'%Y-%m-%d-%H:%M'`

table(){

mysqldump --host=$FROM_IP -u$FROM_USER -p$FROM_PASSWD --databases $FROM_DATABASE --table $TABLES > $BACKUP_DIR/$1_$DATE.sql

}

databases(){

mysqldump --host=$FROM_IP -u$FROM_USER -p$FROM_PASSWD --databases $FROM_DATABASE > $BACKUP_DIR/$1_$DATE.sql

}

case $2 in

table)

table $3

;;

database)

databases $3

;;

*)

echo "USAGE: $0 table|database backup-mark"

echo "e.g.: $0 device_training_record test"

exit 1;

;;

esac

~~~

脚本配置文件

~~~

#备份数据保存位置

BACKUP_DIR='/data/backup/mysql'

#源数据库

FROM_IP='192.168.56.130'

FROM_USER='root'

FROM_PASSWD='tuna'

#要备份的数据库以空格分隔

FROM_DATABASE='mybatis laonanhai'

#要备份的表以空格分隔

TABLES=''

~~~

5. 调用jar

java -jar 参数。。。。

~~~

java -jar App.jar /home/tuna/shell/mysql/mysqlbackup.sh /home/tuna/shell/mysql/backup.properties database hellomysql

~~~

 类似资料: