1、容器需要先执行source命令,有权限限制的需要先打通互信。
2、复杂的shell命令,如重定向,需要传入数组。
public void excuteLinuxCmd(String cmd) {
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(cmd);
InputStream errorStream = process.getErrorStream();
StringBuffer out = new StringBuffer();
byte[] b = new byte[1024];
int len = 0;
while ((len = errorStream.read(b)) != -1) {
out.append(new String(b, 0, len));
}
logger.info("cmd:" + cmd);
logger.info("命令执行:" + out.toString());
errorStream.close();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
public void excuteLinuxCmdArr(String[] cmd) {
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(cmd);
InputStream errorStream = process.getErrorStream();
StringBuffer out = new StringBuffer();
byte[] b = new byte[1024];
int len = 0;
while ((len = errorStream.read(b)) != -1) {
out.append(new String(b, 0, len));
}
logger.info("cmd:" + cmd);
logger.info("命令执行:" + out.toString());
errorStream.close();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
public Object openstackBackups(Long regionId) {
Sdn sdn = vpcServiceImpl.getSdnByRegionId(regionId);
String openstackMysqlIp = sdn.getOpenstackMysqlIp();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmm");
String date = df.format(new Date());
Listlist = new ArrayList<>();
list.add("ssh");
list.add("root@" + openstackMysqlIp);
list.add("/usr/lib/bcrdb/bin/mysqldump");
list.add("-pAAA");
list.add("--all-databases");
list.add("--set-gtid-purged=OFF > /data/mysql-dump/dxy/" + date + ".sql");
excuteLinuxCmdArr(list.toArray(new String[list.size()]));
logger.info("openstack备份成功");
return list;
}
//查看文件是否存在
public int isExist(Long regionId, String fileName) {
Sdn sdn = vpcServiceImpl.getSdnByRegionId(regionId);
String openstackMysqlIp = sdn.getOpenstackMysqlIp();
String resp =
excuteLinuxCmd("ssh root@" + openstackMysqlIp + " ls /data/mysql-dump/dxy/" + fileName);
if ("".equals(resp)) {
return 1;
}
return 0;
}