telnet to Host

本脚本实现telnet连接到特定主机

首先通过telnet程序登录一次,记录下telnet过程中Server返回的提示信息,便于python脚本中做是否已呈现相应步骤的判断条件,如屏幕出现‘login:’应输入username,出现“Password:”时应输入password,出现“~]$”提示符则表明已成功登录。

以下是telnet过程完整log:


Kernel 3.10.0-514.2.2.el7.x86_64 on an x86_64

itop login: yanw

Password:

Last login: Tue Jun 13 15:42:14 from ::ffff:192.168.8.179

[yanw@itop ~]$ ls

test.file  try.py

[yanw@itop ~]$


通过Python实现以上过程,需要调用telnetlib库,以下是面向过程的代码实现:


#-*- coding:utf-8 -*-

'''

Created on 2017年6月13日

Telnet to remote host

@author: will

'''

import telnetlib


Host = '192.168.8.82'

username = 'yanw'

password = 'will392891'

finish = '~]$'          #login successfully

#telnet to host

tn = telnetlib.Telnet(Host)

print tn

#Enter username

print tn.read_until('login:', 5)

tn.write(username + '\n')

#Enter passwd

print tn.read_until('Password:', 5)

tn.write(password + '\n')

#Check if login successfuly

print tn.read_until(finish, 5)

print tn.write('ls' + '\n')

#close the connection

tn.close()


简单封装成Class:

#-*- coding:utf-8 -*-

'''

Created on 2017年6月13日

@author: will

'''

import telnetlib

from _pyio import __metaclass__

__metaclass__

class telnetOO():

'''

Telnet to remote host

'''

def connect(self, Host, Username, Password, SuccessCheck):

tn = telnetlib.Telnet(Host)

#print tn

tn.read_until('login:', 1)

print tn.read_until('login:', 1)

tn.write(Username + '\n')

tn.read_until('Password:', 1)

print tn.read_until('Password:', 1)

tn.write(Password + '\n')

#print tn.read_until(SuccessCheck, 5)

try:

tn.read_until('~]$', 1)

print 'Login success !'

except:

print 'Login failed , Please check the Username or Passwd !'

else:

pass

if __name__ == '__main__':

session = telnetOO()

print 'Telent to 192.168.82,with username:yanw & Passwd:will392891'

log = session.connect('192.168.8.82', 'yanww', 'will392891', '~]$')

执行结果:

Telent to 192.168.82,with username:yanw & Passwd:will392891

Login success !



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容