天天看點

python telnetlib詳解 執行循環指令_python執行telnet指令

一個簡單的用python執行telnet指令的例子

# -*- coding: mbcs -*-

import telnetlib

import ipAddress

import sys

host='122.224.113.164'

port = 20001

command='showall'

timeout = 2

def telnet():

global command

try:

tn = telnetlib.Telnet(host,port) #連接配接端綁定到主機 HOST 去

except:

print "Cannot open host"

return

tn.write(command+'\r\n')

msg = tn.read_until("$",timeout)

tn.write("exit\r\n")

tn.close()

print msg

cont = raw_input("\ncommand>")

if cont != '':

command = cont

show()

def help():

print """python telnet.py [host=] [port=] [timeout=] [command=]"""

if __name__ == "__main__":

if len(sys.argv) >= 2: # additional parameters

for arg in sys.argv[1:]:

pv=arg.split("=")

if len(pv)!=2:

help()

sys.exit()

if pv[0] == "min":

min=int(pv[1])

elif pv[0] == "host":

host=pv[1]

elif pv[0] == "port":

port = int(pv[1])

elif pv[0] == "command":

command = pv[1]

elif pv[0] == "timeout":

timeout = int(pv[1])

else:

help()

sys.exit()

show()