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 !



最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容