詳解python連接telnet和ssh的兩種方式
發(fā)布日期:2021-12-17 08:16 | 文章來源:腳本之家
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)
#發(fā)送命令 登錄,用戶名: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') #執(zhí)行指令
time.sleep(1)
handle.write('sys\n') #執(zhí)行指令
time.sleep(1)
handle.write('display running-config\n') #執(zhí)行指令
time.sleep(1)
handle.write('show stack\n') #執(zhí)行指令
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服務(wù)器
client.connect("192.168.10.1",22,"admin","admin")
#執(zhí)行命令的方式一連接linux發(fā)送固定指令
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())
#執(zhí)行命令的方式二 獲取命令行參數(shù),并且刪除參數(shù)1.保留需要執(zhí)行的命令
buf = sys.argv
del buf[0]
str1 = ' '.join(buf)
print(str1)
#執(zhí)行命令行參數(shù)給出的命令
stdin,stdout,stderr = client.exec_command(str1)
#time.sleep(1)
print(stdout.read())
到此這篇關(guān)于詳解python連接telnet和ssh的兩種方式的文章就介紹到這了,更多相關(guān)python連接telnet和ssh內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信