티스토리 뷰
[JAVA] Switch Config Backup Program
- 동작 OS : Linux / Windows
- import Library : TelnetClient in commons-net-3.5.jar
- 클래스 내용 :
TodayDate Class에서 오늘 날짜를 구함(yyyy-mm-dd 형식)
SaveConfig Class에서 config result를 저장
CreateDir Class에서 Config가 저장될 디렉토리를 생성함
ConfigBackup Class에 Telnet 관련 메소드가 정의되어 있으며, Switch Arrary List를 포함함.
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;
import org.apache.commons.net.telnet.TelnetClient;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
*
* Made by gukii.tistory.com
* Switch Auto Backup Program
* Applied Switch Vendors : Cisco, Alaxa, Huawei
* Hit rate : 100%
*/
public class ConfigBackup {
// Switch Array List
// Do not Modify Switch Array List!!
// In the main method, use the sequence of the switch array as a constant value.
// !!!! Just add a new switch at the bottom of the array !!!!
private static String[][] swarray = {
// Cisco Switch
{ "hostname", "IP", "Cisco", "alias" }, // { hostname, IP, Cisco || Huawei || Alaxa, Switch Alias }
// Huawei Switch
{ "hostname", "IP", "Huawei", "alias" },
// Alaxa Switch
{ "hostname", "IP", "Alaxa", "alias" },
{ "hostname", "IP", "Alaxa", "alias" }
};
private static String id = "(Put in ID)";
private static String pw = "(Put in PW)";
private static int i=0; // Arrary Scan value i
private TelnetClient telnet = new TelnetClient();
private InputStream in = null;
private PrintStream out = null;
private char prompt = '>';
// ConfigBackupV1.0 Constructor
public ConfigBackup() {}
/** ConfigBackupV1.0 Object Connects to : Alaxa */
public void Alaxa_connect(String server, String user, String password) {
try {
// telnet Connect Method
telnet.connect(server, 23);
// in, out field Assignment
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Connect to Alaxa
readUntil("login: ");
write(user);
readUntil("Password:");
write(password);
prompt = '>';
// Wait prompt
readUntil(prompt + " ");
} catch (Exception e) {
System.out.println("Connect Error!");
e.printStackTrace();
}
}
/** ConfigBackupV1.0 Object Connects to : Cisco L3 */
public void CiscoL3_connect(String server, String user, String password) {
try {
// telnet Connect Method of Cisco L3
telnet.connect(server, 23);
// in, out field Assignment
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Connect to Cisco L3
readUntil("Username: ");
write(user);
readUntil("Password: ");
write(password);
prompt = '>';
// Wait prompt
readUntil(prompt + "");
} catch (Exception e) {
System.out.println("Connect Error!");
e.printStackTrace();
}
}
/** ConfigBackupV1.0 Object Connects to : Cisco */
public void Cisco_connect(String server, String password) {
try {
// telnet connect Method
telnet.connect(server, 23);
// in, out field Assignment
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Login
readUntil("Password: ");
write(password);
prompt = '>';
// wait prompt
readUntil(prompt + "");
} catch (Exception e) {
System.out.println("Connect Error!");
e.printStackTrace();
}
}
/** ConfigBackupV1.0 Object Connects to : Huawei L2 */
public void Huawei_connect(String server, String password) {
try {
// telnet connect method
telnet.connect(server, 23);
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
readUntil("Password:");
write(password);
prompt = '>';
readUntil(prompt + "");
} catch (Exception e) {
System.out.println("Connect Error!");
e.printStackTrace();
}
}
/** ConfigBackupV1.0 Object Connects to : Huawei L3 */
public void HuaweiL3_connect(String server, String user, String password) {
try {
telnet.connect(server, 23);
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
readUntil("Username:");
write(user);
readUntil("Password:");
write(password);
prompt = '>';
readUntil(prompt + "");
} catch (Exception e) {
System.out.println("Connect Error!");
e.printStackTrace();
}
}
/**
* Swtich to superuser
* @param password : Password of superuser
* @exception
*/
public void en(String password) {
try {
write("en");
readUntil("Password: ");
write(password);
prompt = '#';
if( swarray[i][2].equals("Alaxa") )
readUntil( prompt + " ");
else if( swarray[i][2].equals("Cisco") || swarray[i][2].equals("CiscoL3") )
readUntil( prompt + "");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Swtich to superuser (Huawei Switch)
* @param password : Password of superuser
* @exception
*/
public void su(String password) {
try {
write("su");
if( swarray[i][2].equals("Huawei"))
readUntil(" Password:");
else if ( swarray[i][2].equals("HuaweiL3"))
readUntil("Password:");
write(password);
readUntil( prompt + "");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param pattern : Hostname + prompt
* @return java.lang.String
*/
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length() - 1);
StringBuffer sb = new StringBuffer();
//boolean found = false;
char ch = (char)in.read();
while(true) {
System.out.print(ch);
sb.append(ch);
if(ch == lastChar) {
if(sb.toString().endsWith(pattern)) {
return sb.toString();
}
}
ch = (char)in.read();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
if( swarray[i][2].equals("Alaxa") )
return readUntil(swarray[i][0] + prompt + " ");
else if( swarray[i][2].equals("Cisco") || swarray[i][2].equals("CiscoL3") )
return readUntil(swarray[i][0] + prompt + "");
else if(command.equals("system-view"))
return readUntil(swarray[i][0] + "]" + "");
else if(command.equals("user-interface vty 0 4") || command.equals("screen-length 0") || command.equals("undo screen-length" ))
return readUntil(swarray[i][0] + "-ui-vty0-4]" + "");
else if( swarray[i][2].equals("Huawei") || swarray[i][2].equals("HuaweiL3") )
return readUntil(swarray[i][0] + ">" + "");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Telnet disconnect Method
*/
public void disconnect() {
try {
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
// Main Method
public static void main(String args[])
{
ConfigBackup telnet = new ConfigBackup(); // Create ConfigBackup class object(Telnet)
String result = null; // Telnet command result
SaveConfig save = new SaveConfig();
CreateDir dir = new CreateDir();
dir.createDirec(); // Create Directory Before saving SwitchConfig
for(i=0; i<swarray.length; i++)
{
// Cisco Switch Config Backup
if(swarray[i][2].equals("Cisco"))
{
try {
telnet.Cisco_connect(swarray[i][1], pw );
telnet.en(pw);
telnet.sendCommand("terminal length 0");
result=telnet.sendCommand("sh run");
telnet.disconnect();
save.setHostname(swarray[i][0]);
save.setResult(result);
System.out.println("");
} catch(Exception e) {
result="Connection Failed!";
save.setHostname(swarray[i][0]);
save.setResult(result);
}
}
// CiscoL3 Switch Config Backup
if(swarray[i][2].equals("CiscoL3"))
{
try {
telnet.Cisco_connect(swarray[i][1], "(Put in Password)" );
telnet.en("(Put in Password)");
telnet.sendCommand("terminal length 0");
result=telnet.sendCommand("sh run");
telnet.disconnect();
save.setHostname(swarray[i][0]);
save.setResult(result);
System.out.println("");
} catch(Exception e) {
result="Connection Failed!";
save.setHostname(swarray[i][0]);
save.setResult(result);
}
}
// Alaxa Switch Config Backup
else if(swarray[i][2].equals("Alaxa"))
{
try {
telnet.Alaxa_connect(swarray[i][1], id, pw );
telnet.en(pw);
telnet.sendCommand("set terminal pager disable");
result=telnet.sendCommand("sh run");
telnet.sendCommand("set terminal pager enable");
telnet.disconnect();
save.setHostname(swarray[i][0]);
save.setResult(result);
System.out.println("");
} catch(Exception e) {
result="Connection Failed!";
save.setHostname(swarray[i][0]);
save.setResult(result);
}
}
// Huawei L3 Switch Config Backup
else if(swarray[i][2].equals("HuaweiL3"))
{
try {
telnet.HuaweiL3_connect(swarray[i][1], id, "(Put in Password)" );
telnet.su("(Put in Password)");
//telnet.sendCommand("terminal length 0");
telnet.sendCommand("system-view");
telnet.sendCommand("user-interface vty 0 4");
telnet.sendCommand("screen-length 0");
telnet.sendCommand("return");
result=telnet.sendCommand("dis cu");
telnet.sendCommand("system-view");
telnet.sendCommand("user-interface vty 0 4");
telnet.sendCommand("undo screen-length");
telnet.sendCommand("return");
telnet.disconnect();
save.setHostname(swarray[i][0]);
save.setResult(result);
System.out.println("");
} catch(Exception e) {
result="Connection Failed!";
save.setHostname(swarray[i][0]);
save.setResult(result);
}
}
// Huawei Switch Config Backup
else if(swarray[i][2].equals("Huawei"))
{
try {
telnet.Huawei_connect(swarray[i][1], pw );
telnet.su(pw);
//telnet.sendCommand("terminal length 0");
telnet.sendCommand("system-view");
telnet.sendCommand("user-interface vty 0 4");
telnet.sendCommand("screen-length 0");
telnet.sendCommand("return");
result=telnet.sendCommand("dis cu");
telnet.sendCommand("system-view");
telnet.sendCommand("user-interface vty 0 4");
telnet.sendCommand("undo screen-length");
telnet.sendCommand("return");
telnet.disconnect();
save.setHostname(swarray[i][0]);
save.setResult(result);
System.out.println("");
} catch(Exception e) {
result="Connection Failed!";
save.setHostname(swarray[i][0]);
save.setResult(result);
}
}
}
}
}
class CreateDir {
TodayDate date = new TodayDate();
// path Example
// Windows -> C:\\Users\\gukii\\Documents\\test\\
// Linux -> /home/test/test/
//
private String path = "(Put in Save Directory Path)" + date.getDate();
File f = new File(path);
public CreateDir() {} // Constructor of CreateDir class
public void createDirec()
{
if(!f.exists())
{
f.mkdirs();
path = "(Put in Save Directory Path)" + date.getDate();
}
else
path = "(Put in Save Directory Path)" + date.getDate();
}
public String getDir()
{
return this.path;
}
}
class SaveConfig {
private String result = null;
CreateDir dir = new CreateDir();
private String fileName;
public SaveConfig() {} // Constructor of SaveConfig class
public void setResult(String result)
{
this.result=result;
try {
// BufferedWriter and FileWriter Combination
BufferedWriter fw = new BufferedWriter(new FileWriter(fileName,false)); // false Option means that do not permit add to end
// Write SwtichConfig in File
fw.write(result);
fw.flush();
// Close fw Object
fw.close();
}catch(Exception e) {
e.printStackTrace();
}
}
public void setHostname(String hostname)
{
// If you use Linux OS, Put in "/" after dir.getDir(). If you use Windows OS, Put in "\\" after dir.getDir()
fileName = dir.getDir() + "/" + hostname + ".log";
}
}
class TodayDate {
Date d = new Date();
public TodayDate() {} // Constructor of TodayDate class
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public String getDate()
{
return sdf.format(d);
}
}
이제 해당 java 파일을 원하는 시간에 실행시키고 백업하길 원한다면, 아래 링크 참조!!
2. 2018/06/19 - [Programming/Shell Script] - [Shell Script] Backup Shell Script
3. 2018/06/19 - [Programming/Python] - [Python] Telegram Bot을 이용한 백업결과 전송
'Programming > JAVA' 카테고리의 다른 글
| 외부 library(jar 파일) import 하여 JAVA 프로그램 실행시키기 (0) | 2018.08.14 |
|---|---|
| [JAVA] 일회용 패스워드 생성기(OTP Creator) (0) | 2018.08.14 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 매치스패션 할인
- 이지 350 지브라
- end 응모
- 케니4
- selinux 설명
- 이지 부스트 700 모브
- 리눅스 hostname 변경
- 웹쉘 예방
- 이지 700 모브
- linux bridge 설정
- 이지 부스트 700
- 배트멍 할인
- selinux 사용법
- 리눅스 모니터링
- selinux 정책설정
- 리니지m 격수 팁
- 웹쉘 탐지
- Java
- troijan
- 파워쉘 문자열 포함 조건
- 나이키 켄드릭라마
- 피파온라인4
- CloudStack
- 웹쉘 해결
- 파워쉘 문자열
- 나이키 코르테즈
- 조던1 사틴 블랙토
- 조던1 사틴 블랙토 개봉기
- 파워쉘 문자열 포함
- 조던1 사틴
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함
commons-net-3.5.jar