本腳本實(shí)現(xiàn)telnet連接到特定主機(jī)
首先通過(guò)telnet程序登錄一次,記錄下telnet過(guò)程中Server返回的提示信息,便于python腳本中做是否已呈現(xiàn)相應(yīng)步驟的判斷條件,如屏幕出現(xiàn)‘login:’應(yīng)輸入username,出現(xiàn)“Password:”時(shí)應(yīng)輸入password,出現(xiàn)“~]$”提示符則表明已成功登錄。
以下是telnet過(guò)程完整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 ~]$
通過(guò)Python實(shí)現(xiàn)以上過(guò)程,需要調(diào)用telnetlib庫(kù),以下是面向過(guò)程的代碼實(shí)現(xiàn):
#-*- 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()
簡(jiǎn)單封裝成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', '~]$')
執(zhí)行結(jié)果:
Telent to 192.168.82,with username:yanw & Passwd:will392891
Login success !