import paramiko
import telegram
from telegram.ext import Updater
import schedule
import time
import asyncio
def get_switch_info(host :str, port :int, username :str, password :str) -> tuple:
with paramiko.SSHClient() as ssh:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
hostname=host, port=port, username=username, password=password,
look_for_keys=False,
allow_agent=False)
shell = ssh.invoke_shell()
time.sleep(1)
shell.send('enable\n')
time.sleep(1)
shell.send(f'{password}\n')
time.sleep(1)
shell.send('terminal length 0\n')
time.sleep(1)
shell.send('show version\n')
time.sleep(1)
version_output = shell.recv(65535).decode('utf-8')
shell.send('show logging\n')
time.sleep(1)
log_output = shell.recv(65535).decode('utf-8')
shell.send('show running-config\n')
time.sleep(2)
run_output = shell.recv(65535).decode('utf-8')
return version_output, log_output, run_output
def save_file(message: str) -> None:
with open('switch_info.txt', 'w') as file:
file.write(message)
async def send_file(bot: telegram.Bot, file: str, chat_id: str) -> None:
await bot.send_document(chat_id=chat_id, document=open(file=file, mode='rb'))
async def send_message(bot: telegram.Bot, message: str, chat_id: str) -> None:
await bot.send_message(chat_id=chat_id, text=message)
async def main() -> None:
TELEGRAM_TOKEN :str =''
TELEGRAM_CHATID :str =''
bot = telegram.Bot(token=TELEGRAM_TOKEN)
HOST :str = ''
PORT :int = 22
USERNAME :str = ''
PASSWORD :str = ''
version, log, config= get_switch_info(host=HOST, port=PORT, username=USERNAME, password=PASSWORD)
message = f"[Switch Info]\n{version}\n\n[Switch loggging]\n{log}\n\n[Switch config]\n{config}"
save_file(message=message)
await send_message(bot=bot, message=f"[{HOST}] 장비 알람 도착!\n", chat_id=TELEGRAM_CHATID)
await send_file(bot=bot, file='switch_info.txt', chat_id=TELEGRAM_CHATID)
if __name__ == '__main__':
asyncio.run(main())