# -*-encoding:utf-8 -*-
"""
@Time : 2022/12/30 10:10
@Auth : ruqing
@File :ssh_sonic.py
@IDE :PyCharm
@Motto:ABC(Always Be Coding)
"""
import sys, logging
import os
import time
from paramiko.client import SSHClient, AutoAddPolicy
from paramiko import AuthenticationException
from paramiko.ssh_exception import NoValidConnectionsError
class SshClient():
def __init__(self):
self.ssh_client = SSHClient()
if not os.path.exists('log'):
os.mkdir('log')
# 生成log文件名
datefmt = '%Y%m%d-%H%M%S'
strftime = time.strftime(datefmt)
self.logname = './log/' + '6865_sonic' + '-' + strftime + '.log'
def ssh_login(self, host_ip, username, password):
try:
self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
self.ssh_client.connect(host_ip, port=2081, username=username, password=password)
except AuthenticationException:
logging.warning('username or password error')
return 1001
except NoValidConnectionsError:
logging.warning('connect time out')
return 1002
except:
print("Unexpected error:", sys.exc_info()[0])
return 1003
return 1000
def execute_some_command(self, command):
stdin, stdout, stderr = self.ssh_client.exec_command(command)
result = (stdout.read().decode())
self.log(result)
return result
def ssh_logout(self):
self.ssh_client.close()
def log(self, string):
if string.strip() == '':
return
formatter = logging.Formatter('%(asctime)s %(message)s', datefmt='%Y%m%d-%H%M%S--')
ch = logging.StreamHandler()
ch.setFormatter(formatter)
fh = logging.FileHandler(self.logname)
fh.setFormatter(formatter)
formatter2 = logging.Formatter('%(message)s')
ch2 = logging.StreamHandler()
ch2.setFormatter(formatter2)
fh2 = logging.FileHandler(self.logname)
fh2.setFormatter(formatter2)
ch3 = logging.StreamHandler()
ch3.setFormatter(formatter)
ch3.terminator = ''
fh3 = logging.FileHandler(self.logname)
fh3.setFormatter(formatter)
fh3.terminator = ''
logger = logging.getLogger('mylogger1')
logger.setLevel(logging.INFO)
logger.addHandler(ch)
logger.addHandler(fh)
logger2 = logging.getLogger('mylogger2')
logger2.setLevel(logging.INFO)
logger2.addHandler(ch2)
logger2.addHandler(fh2)
logger3 = logging.getLogger('mylogger3')
logger3.setLevel(logging.INFO)
logger3.addHandler(ch3)
logger3.addHandler(fh3)
string = string.split('\n')
logger2.info(string[0].strip('\r').strip('\n'))
if len(string) >= 2:
for i in range(1, len(string) - 1):
logger.info(string[i].strip('\r').strip('\n'))
logger3.info(string[-1].strip('\r').strip('\n'))
logger.removeHandler(ch)
logger.removeHandler(fh)
logger2.removeHandler(ch2)
logger2.removeHandler(fh2)
logger3.removeHandler(ch3)
logger3.removeHandler(fh3)
if __name__ == "__main__":
ssh = SshClient()
for i in range(10000):
ssh.log('*************************{}****************************'.format(i + 1))
if ssh.ssh_login(host_ip="192.168.107.62", username="adminadmin", password="******") == 1000:
ssh.execute_some_command('sudo reboot -y')
ssh.ssh_logout()
time.sleep(100)
if ssh.ssh_login(host_ip="192.168.107.62", username="adminadmin", password="******") == 1000:
ssh.execute_some_command(command='timedatectl')
ssh.execute_some_command(command='sudo docker ps -a')
check = ssh.execute_some_command(command='lspci |grep "Broadcom"')
if 'Gigabit Ethernet PCIe' not in check:
ssh.log('脚本停止执行,请查看日志')
ssh.log('!!!!!!!!!!!!!!!!!!!!!!!!!!')
break
ssh.ssh_logout()