使用Java管理千臺規模Linux服務器 |
發布時間: 2012/8/20 17:31:44 |
前東家是一家游戲公司,老板很好,當時工作也留下了很多自己原創的管理腳本。現在分享一下在辦公環境使用Java、Jsch登錄VPN管理Linux的腳本(此處實現JAVA調用Linux上備份Mysql的shell作為示例),希望對運維的朋友有幫助,盡快從繁雜的服務器管理工作中脫離出來。 主要的實現思路: 如果需要先登錄VPN才能連接游戲服務器,需要將游戲服務器的ssh端口(一般是22)映射到本地辦公電腦的端口上(如5555),然后ssh連接本地辦公電腦的5555端口,這樣就可以連接到游戲服務器,并可以管理游戲服務器了。 當您學會通過VPN連接Linux服務器后,如果只在內網環境,不使用VPN,就更簡單了,此外不再詳述。Jsch的example里也有介紹。 代碼:使用Jsch透過VPN 1.package com.daily.wednesday; 2.import java.io.IOException; 3.import java.io.InputStream; 4.import java.sql.Connection; 5.import java.sql.DriverManager; 6.import java.sql.ResultSet; 7.import java.sql.SQLException; 8.import java.sql.Statement; 9.import com.daily.util.DataBaseConnection; 10.import com.jcraft.jsch.Channel; 11.import com.jcraft.jsch.ChannelExec; 12.import com.jcraft.jsch.JSch; 13.import com.jcraft.jsch.JSchException; 14.import com.jcraft.jsch.Session; 15.public class BackUpMysql3 { 16. public static void main(String args[]) { 17. // 讀取數據庫配置 18. DataBaseConnection dataBaseConnection = new DataBaseConnection(); 19. String dataBaseConfigForWrite[] = new String[3]; 20. dataBaseConfigForWrite = dataBaseConnection.loadDataConfig(); 21.22. Connection conn = null;// 數據庫連接 23. Statement stmt = null;// 數據庫表達式 24. ResultSet rs = null; // 結果集 25. int rowcount = 0;// 總記錄數 26. String sql = "select * from servers_maint_wednesday"; 27.28. try { 29. conn = DriverManager.getConnection(dataBaseConfigForWrite[0], 30. dataBaseConfigForWrite[1], dataBaseConfigForWrite[2]); 31. stmt = conn.createStatement(); 32. rs = stmt.executeQuery(sql); 33. rs.last(); 34. rowcount = rs.getRow();// 總記錄數 35. rs = stmt.executeQuery(sql); 36. } catch (SQLException e) { 37. e.printStackTrace(); 38. } 39. // 定義游戲服務器IP的數組,游戲服務器IP存在數據庫中。 40. String privateIpaddress[] = new String[rowcount]; 41. String remark[] = new String[rowcount];// 定義游戲區名稱 42. String programPath[] = new String[rowcount];// 定義程序路徑 43. String backMysqlShellPath[] = new String[rowcount];// 定義mysql備份腳本路徑 44.45. int j = 0; 46. try { 47. while (rs.next()) { 48. privateIpaddress[j] = rs.getString("privateipaddress"); 1 50. programPath[j] = rs.getString("programpath"); 51. backMysqlShellPath[j] = rs.getString("backmysqlshellpath"); 52. j++; 53. } 54. } catch (Exception e) { 55. e.printStackTrace(); 56. } finally { 57. try { 58. if (rs != null) { 59. rs.close(); 60. } 61. if (stmt != null) { 62. stmt.close(); 63. } 64. if (conn != null) { 65. conn.close(); 66. } 67. } catch (Exception e) { 68. e.printStackTrace(); 69. } 70. } 71.72. // 調用mysql備份方法
本文出自:億恩科技【www.laynepeng.cn】 |