目录
  • telnet 连接方式
  • ssh连接方式

telnet 连接方式

#!/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')

ssh连接方式

#!/usr/bin/env python
# coding=utf-8
 
import paramiko,sys,time
 
client = paramiko.sshclient()
client.set_missing_host_key_policy(paramiko.autoaddpolicy())
#连接ssh服务器
client.connect("192.168.10.1",22,"admin","admin")
#执行命令的方式一   连接linux发送固定指令
stdin,stdout,stderr = client.exec_command("whoami")
time.sleep(2)
print(stdout.read())
stdin,stdout,stderr = client.exec_command("cat /root/lzhi/c_call_python.txt")
print(stdout.read())
stdin,stdout,stderr = client.exec_command("ls")
print(stdout.read())
stdin,stdout,stderr = client.exec_command("ls -la")
print(stdout.read())
 
#执行命令的方式二  获取命令行参数,并且删除参数1.保留需要执行的命令
buf = sys.argv
del buf[0]
str1 = ' '.join(buf)
print(str1)
#执行命令行参数给出的命令
stdin,stdout,stderr = client.exec_command(str1)
#time.sleep(1)
print(stdout.read())

到此这篇关于详解python连接telnet和ssh的两种方式的文章就介绍到这了,更多相关python连接telnet和ssh内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!