Вот краткий обзор функциональности скрипта:
1. Он устанавливает SSH-соединение с удаленным сервером.
2. Он выполняет сценарий bash, расположенный на сервере. Этот сценарий bash переходит в каталог расположения резервных копий и ищет резервные копии, созданные за последние 48 часов. Если резервная копия не найдена, выводится сообщение об ошибке.
3. Выходные данные сценария bash отправляются обратно в сценарий Python, который записывает эти выходные данные в файл Excel. документ с использованием библиотеки openpyxl.
Проблема возникает при попытке запустить скрипт более одного раза. После первоначального успешного выполнения последующие попытки приводят к ошибке.
Скрипт Python:
Код: Выделить всё
import openpyxl
import os
import subprocess
# location of the excel document
location = '/nfs/commonshare/SCRIPT-DEVELOPING'
filename = 'test-check.xlsx'
filepath = os.path.join(location, filename)
# BACKUP AUTOMATIC CHECKING
# SSH connection information
commands = [
"sshpass -p 'password1' ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no -o StrictHostKeyChecking=no username1@host1 '/home/location1/test1.sh' 2>/dev/null",
"sshpass -p 'password2' ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no -o StrictHostKeyChecking=no username2@host2 '/home/location2/test2.sh' 2>/dev/null",
"sshpass -p 'password3' ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no -o StrictHostKeyChecking=no username3@host3 '/home/location3/test3.sh' 2>/dev/null"
]
# Load the existing Excel document
wb = openpyxl.load_workbook(filepath, read_only=False)
sheet = wb.active
for row in sheet.iter_rows():
for cell in row:
cell.value = None
# Starting row for D column
row = 12
# Execute each command one by one
for command in commands:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
output = stdout.decode().splitlines()
# Write the output to the Excel document
for line in output:
if line == "END":
row += 0 # Move to next line when 'END' is encountered
else:
cell_ref = f'D{row}'
sheet[cell_ref] = line # Write data into cell
row += 1 # Move to next line for next backup detail
# Print any errors
if stderr:
print(stderr.decode())
# Save changes to Excel document
wb.save(filepath)
Код: Выделить всё
15 is out of range
Traceback (most recent call last):
File "checklist-script.py", line 24, in
wb = openpyxl.load_workbook(filepath, read_only=False)
File "/usr/local/lib/python3.6/site-packages/openpyxl/reader/excel.py", line 348, in load_workbook
reader.read()
File "/usr/local/lib/python3.6/site-packages/openpyxl/reader/excel.py", line 301, in read
apply_stylesheet(self.archive, self.wb)
File "/usr/local/lib/python3.6/site-packages/openpyxl/styles/stylesheet.py", line 198, in apply_stylesheet
stylesheet = Stylesheet.from_tree(node)
File "/usr/local/lib/python3.6/site-packages/openpyxl/styles/stylesheet.py", line 103, in from_tree
return super(Stylesheet, cls).from_tree(node)
File "/usr/local/lib/python3.6/site-packages/openpyxl/descriptors/serialisable.py", line 103, in from_tree
return cls(**attrib)
File "/usr/local/lib/python3.6/site-packages/openpyxl/styles/stylesheet.py", line 94, in __init__
self.named_styles = self._merge_named_styles()
File "/usr/local/lib/python3.6/site-packages/openpyxl/styles/stylesheet.py", line 114, in _merge_named_styles
self._expand_named_style(style)
File "/usr/local/lib/python3.6/site-packages/openpyxl/styles/stylesheet.py", line 124, in _expand_named_style
xf = self.cellStyleXfs[named_style.xfId]
File "/usr/local/lib/python3.6/site-packages/openpyxl/styles/cell_style.py", line 189, in __getitem__
return self.xf[idx]
IndexError: list index out of range
Код: Выделить всё
/nfs/commonshare/SCRIPT-DEVELOPINGПодробнее здесь: https://stackoverflow.com/questions/787 ... a-document