评论

收藏

[Linux] 简单介绍python连接telnet和ssh的两种方式

服务系统 服务系统 发布于:2022-08-05 13:40 | 阅读数:543 | 评论:0

#!/usr/bin/env python# coding=utf-8
import time
import telnetlib
import logging
__author__ = 'Evan'
save_log_path = 'result.txt'
file_mode = 'a+'
format_info = '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 添加记录 记录器功能
fh = logging.FileHandler(save_log_path, mode=file_mode)
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter(format_info))
logger.addHandler(fh)
# 增加显示 记录器功能
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter(format_info))
logger.addHandler(ch)
def telnet_handle(host='', port=''):
handle = telnetlib.Telnet(host, port, timeout=10)
handle.set_debuglevel(2)  # Display connect info (send command & received info)
logger.debug('Connect host: {} port: {} successful'.format(host, port))
try:
#获取登录提示‘login:' 后输入密码。
handle.read_until('login:', timeout=5)
#发送命令 登录,用户名:admin 密码:admin
handle.write('admin\n')  #用户名
#如果有输入密码的提示符可以打开这一条,并修正确的密码提示符
#handle.read_until('输入密码提示符', timeout=5)
time.sleep(1)
handle.write('admin\n')  #密码
time.sleep(1)
handle.write('en\n')  #执行指令
time.sleep(1)
handle.write('sys\n')  #执行指令
time.sleep(1)
handle.write('display running-config\n')  #执行指令
time.sleep(1)
handle.write('show stack\n')  #执行指令
time.sleep(1)
#读取所有信息
result = handle.read_very_eager()
logger.info('Received info: {}'.format(result))
finally:
handle.close()
if __name__ == '__main__':
telnet_handle(host='192.168.10.1', port='23')

关注下面的标签,发现更多相似文章