Python+Selenium backup device configuration
Since I knew Python in 2016, I only used telnet or ssh to operate network devices to automatically execute commands. I was basically helpless against web interface devices. Until recently, the company was all deeply convinced devices. The background was ssh. Sorry, it was not open to customers. SNMP only provided a few. To operate in batches, the deeply convinced suggestion was to buy a centralized manager and unify the device version. I went to NM. Later found Python can be used crawler, and later found Selenium such a thing, automatically on the device on a variety of points, the following is a device operation code
#coding:utf-8
import os
import time
import shutil
from selenium import webdriver
options = webdriver.ChromeOptions()
prefs = {'profile.default_content_settings.popups':0,'download.default_directory':'E:/python/file/'}
print prefs
options.add_experimental_option('prefs',prefs)
driver = webdriver.Chrome(executable_path='E:\python\soft\chromedriver.exe',chrome_options=options)
time.sleep(5)
driver.get('https://10.0.0.1')
time.sleep(5)
username = driver.find_element_by_id('user')
username.send_keys('admin')
password = driver.find_element_by_id('password')
password.send_keys('xxxxxx')
button = driver.find_element_by_id('button')
button.click()
time.sleep(5)
driver.implicitly_wait(10)
driver.switch_to_window(driver.window_handles[-1])
driver.find_element_by_xpath("//*[contains(text(),'system configuration')]").click()
time.sleep(5)
driver.find_element_by_xpath("//*[contains(text(),'configure backup and recovery')]").click()
time.sleep(5)
driver.find_element_by_xpath("//*[contains(text(),'Click to download configuration')]").click()
time.sleep(60)
os.chdir(r'E:\python\file')
confFileName = os.listdir('E:\python\\file')[0]
os.rename(confFileName,'Hostname.bcf')
shutil.move('Hostname.bcf','E:\python\\backup')
driver.quit()
PS. Deep convinced development writing front-end level is really speechless, all kinds of labels without id... Fortunately, Python has a find_element_by_xpath fuzzy query, which can directly locate the required label and then give a click() action.
The rest is to operate all kinds of equipment once, and then adapt the code...
driver.find_element_by_xpath("//*[contains(text(),'label text')]") #Locate labels according to label text
driver.find_element_by_xpath("//*[contains(@id,'extend')]") #Locate tags by tag id
driver.find_element_by_xpath("//*[starts-with(@id,'ex')]") #locate label (label id starts with ex)
driver.find_element_by_xpath("//*[end-with(@id,'nd')]") #locate tag (tag id ends with nd)
driver.find_element_by_xpath("//*[matches (text(),'text ')]") #matches regular expressions