一、首先确保,部署应用的服务器安装sshpass
1、sshpass下载与安装(yum方式安装)
yum install sshpass
若yum安装不上,则用下面方法
https://sourceforge.net/projects/sshpass/files/
or
https://pan.baidu.com/s/1pLNxeLd
or
wget http://sourceforge.net/projects/sshpass/files/latest/download -O sshpass.tar.gz
2、下载后,解压,安装
tar -zxvf sshpass-1.06.tar.gz
cd sshpass-1.06
./configure
make
make install
3、测试命令
sshpass -V(查看版本)
或者
sshpass -p 目标服务器密码 scp /home/file.txt root@目标服务器ip:/home/copy
二、命令准备好后,接下来是java代码实现
主要实现
package com.hp.schedule.common.thread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class SyncThread implements Runnable{
private static final Logger log = LoggerFactory.getLogger("adminLogger");
private String serverIp;
public SyncThread(String serverIp) {
this.serverIp = serverIp;
}
@Override
public void run() {
log.info("开始执行服务器同步-{}",serverIp);
String command = "sshpass -p root scp -r /tmp/html/ root@%s:/tmp/";
Runtime runtime = Runtime.getRuntime();
Process pro = null;
BufferedReader input = null;
PrintWriter output = null;
if( null == runtime ){
return;
}
try{
pro = runtime.exec(String.format(command,serverIp));
input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
//output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
log.info("服务器同步完成-{}",serverIp);
}
catch (IOException ex){
ex.printStackTrace();
}
finally {
try{
if(null != input)
input.close();
}
catch (IOException e){
e.printStackTrace();
}
try{
if(null != output)
output.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
}
调用方式,本例是使用service调用
package com.hp.schedule.service.impl;
import com.hp.schedule.common.thread.SyncThread;
import com.hp.schedule.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class NoticeServiceImpl implements NoticeService {
/**
* 目标服务器IP
*/
@Value("${file.targetIp}")
private String targerIp;
/**
* 任务
*/
@Autowired
private TaskExecutor taskExecutor;
@Override
public void createNoticeFile() {
try{
String[] ips = targerIp.split(",");
for (String ip : ips){//同步不到对应服务器
SyncThread syncThread = new SyncThread(ip);
taskExecutor.execute(syncThread);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
然后按照正常调用方式即能够实现文件夹以及文件复制。