telnet to Host

本腳本實(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 !



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • =========================================================...
    lavor閱讀 3,649評(píng)論 0 5
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,568評(píng)論 19 139
  • win7 cmd管理員權(quán)限設(shè)置 net localgroup administrators 用戶名 /add 把“...
    f675b1a02698閱讀 5,512評(píng)論 0 11
  • (一)基本命令 命令格式: 命令 參數(shù) 1.ls 顯示文件名,等同于dos下dir命令 命令格式:ls [opti...
    飛羽孟德閱讀 2,079評(píng)論 0 3
  • ftp 文件傳輸協(xié)議 跨平臺(tái) 上傳下載文件 vsftpd 工具:非常安全的文件傳輸協(xié)議;默認(rèn)的命令端口21號(hào),數(shù)據(jù)...
    柒夏錦閱讀 4,238評(píng)論 1 9

友情鏈接更多精彩內(nèi)容