最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
python连接telnet和ssh的两种方式代码示例
时间:2022-06-25 01:37:42 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下python连接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('adminn') #用户名
#如果有输入密码的提示符可以打开这一条,并修正确的密码提示符
#handle.read_until('输入密码提示符', timeout=5)
time.sleep(1)
handle.write('adminn') #密码
time.sleep(1)
handle.write('enn') #执行指令
time.sleep(1)
handle.write('sysn') #执行指令
time.sleep(1)
handle.write('display running-confign') #执行指令
time.sleep(1)
handle.write('show stackn') #执行指令
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())
相关文章
- 口袋斗罗大陆孔雀翎升星有什么效果 11-03
- 黑色四叶草魔法帝之道基亚特强度怎么样 11-03
- 二重螺旋溯源石获取途径 11-03
- 鸣潮卜灵技能是什么 卜灵技能爆料 11-03
- 燕云十六声鲮货郎经营增益效果怎么得-鲮货郎经营增益效果获取攻略 11-03
- 五月再见六月你好经典文案句子汇编66句 11-03