引入依赖
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> <scope>compile</scope> </dependency>
import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class RemotePostgreSQLBackup { public static void main(String[] args) { String sshHost = "192.168.11.12"; String sshUsername = "root"; String sshPassword = "123456"; String pgDumpCommand = "pg_dump -U postgres -d db_test -t allproject4490 -f /home/backup_file11.bak"; try { // 创建SSH会话 JSch jsch = new JSch(); Session session = jsch.getSession(sshUsername, sshHost); session.setPassword(sshPassword); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); // 打开SSH通道并执行pg_dump命令 ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); channelExec.setCommand(pgDumpCommand); channelExec.connect(); // 等待命令执行完成 while (!channelExec.isClosed()) { Thread.sleep(1000); } // 关闭通道和会话 channelExec.disconnect(); session.disconnect(); System.out.println("远程数据库备份成功"); } catch (Exception e) { e.printStackTrace(); System.err.println("远程数据库备份失败"); } } }
备份数据命令(allproject4490 是要备份的表名)
pg_dump -U postgres -d geodb -t allproject4490 -f /home/backup_file.bak
数据恢复命令
psql -U postgres -d geodb -f /home/backup_file.bak