1 前言

目前,本篇仅记录前段时间搜索得到的关于python使用Telnet的技术博客,由于受领新任务,未进一步验证和深入研究与应用。

参考链接:

python官网:https://docs.python.org/2/library/telnetlib.html#telnet-example

python调用telnet,登陆远程机器执行命令:https://www.oschina.net/code/snippet_102130_6381

Python使用Telnetlib实现远程操作:https://blog.csdn.net/lingfeng5/article/details/73744698

python中telnetlib模块的使用:https://blog.csdn.net/five3/article/details/8099997

python自动化运维之Telnetlib:https://blog.csdn.net/w1418899532/article/details/82701346

2 原理

3 实践

3.1 通过执行脚本,可以登陆远程机器,并执行命令

!/usr/bin/env python
 
def telnetdo(HOST=None, USER=None, PASS=None, COMMAND=None): #define a function
    import telnetlib, sys
    if not HOST:
        try:
            HOST = sys.argv[1]
            USER = sys.argv[2]
            PASS = sys.argv[3]
            COMMAND = sys.argv[4]
        except:
            print "Usage: telnetdo.py host user pass command"
            return
    msg = ['Debug messages:\n'] #
    tn = telnetlib.Telnet() #
    try:
        tn.open(HOST)
    except:
        print "Cannot open host"
        return
    #msg.append(tn.expect(['login:'], 5)) #
    tn.read_until("login:")
    tn.write(USER + '\n')
    if PASS:
        #msg.append(tn.expect(['Password:'], 5))
        tn.read_until("Password:")
        tn.write(PASS + '\n')
    #msg.append(tn.expect([USER], 5))
    tn.write(COMMAND + '\n')
    tn.write("exit\n")
    #msg.append(tn.expect(['#'], 5))
    tmp = tn.read_all()
    tn.close()
    del tn
    return tmp
     
if __name__ == '__main__':
    print telnetdo()
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-07
猜你喜欢
  • 2022-12-23
  • 2021-10-23
  • 2021-08-29
  • 2022-12-23
相关资源
相似解决方案