JAVA代码实现远程服务器的文件操作

1、 下载svnkit的jar包
网址:https://mvnrepository.com/artifact/org.tmatesoft.svnkit/svnkit
Jar名:svnkit-1.9.0-r10609-atlassian-hosted.jar和svnkit-1.8.12.jar

注:JAVA类中导入jar— com.trilead.ssh2.*
例:
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.ConnectionInfo;
import com.trilead.ssh2.SCPClient;
import com.trilead.ssh2.SFTPv3Client;

2、 实例代码
//【1】建立连接—远程服务器IP和端口号
Connection con = new Connection(“192.168.1.1”, 22);
ConnectionInfo connect = con.connect();
boolean isAuthed = con.authenticateWithPassword(“用户名 “, “密码”);

//【2-1】建立SCP客户端,执行封装的方法
SCPClient scpClient = con.createSCPClient();
//从服务器获取文件
scpClient.get(“/home/test /a.txt”, “C:/test/b.txt”);
//将本地文件上传到服务器
scpClient.put(“C:/test/c.txt “, “/home /test/d.txt”);

//【2-2.1】开启会话,执行原生linux命令
Session session = con.openSession();
//服务器文件移动并改名
session.execCommand(“mv -f /home/test/a.txt /home/test2/b.txt”);
//从服务复制文件到本地(下载)并改名
session.execCommand(“scp [email protected]:/home/test/a.txt /home/test2/b.txt”);
//从本地复制文件到服务器(上传)并改名
session.execCommand(“scp /home/test2/b.txt [email protected]:/home/test/a.txt “);

//【2-2.2】显示执行命令后的信息
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null) {
log.info(“远程服务器返回信息:空”);
break;
}
log.info(“远程服务器返回信息:” + line);
}
//获得退出状态
System.out.println(“ExitCode: ” + session.getExitStatus());
//关闭会话
session.close();

//【3】关闭连接
con.close();

你可能感兴趣的:(服务器,服务器,java,scp,文件操作)