在Python中使用Telnet
要在Python中使用Telnet,我们可以使用telnetlib模块。该模块提供实现Telnet协议的Telnet类。
Telnet模块有几个基础方法,在本示例中,我们将依次介绍这些函数:read_until, read_all()和 write()
Python中的Telnet脚本
一个简单的telnet脚本例程:
import getpass
import sys
import telnetlib
HOST = "hostname"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "
")
if password:
tn.read_until("Password: ")
tn.write(password + "
")
tn.write("ls
")
tn.write("exit
")
print tn.read_all()
更完备的telnet脚本例程:
在ActiveState上,可以找到telnetlib的更多Python脚本,例如以下脚本。有关在Python中使用Telnet客户端的更多信息,请参见官方文件。
在以下例程中,使用Python的标准telnetlib模块将命令发送到一个或多个登录名。
# auto_telnet.py - remote control via telnet
import os, sys, string, telnetlib
from getpass import getpass
class AutoTelnet:
def __init__(self, user_list, cmd_list, **kw):
self.host = kw.get('host', 'localhost')
self.timeout = kw.get('timeout', 600)
self.command_prompt = kw.get('command_prompt', "$ ")
self.passwd = {}
for user in user_list:
self.passwd[user] = getpass("Enter user '%s' password: " % user)
self.telnet = telnetlib.Telnet()
for user in user_list:
self.telnet.open(self.host)
ok = self.action(user, cmd_list)
if not ok:
print "Unable to process:", user
self.telnet.close()
def action(self, user, cmd_list):
t = self.telnet
t.write("\n")
login_prompt = "login: "
response = t.read_until(login_prompt, 5)
if string.count(response, login_prompt):
print response
else:
return 0
password_prompt = "Password:"
t.write("%s\n" % user)
response = t.read_until(password_prompt, 3)
if string.count(response, password_prompt):
print response
else:
return 0
t.write("%s\n" % self.passwd[user])
response = t.read_until(self.command_prompt, 5)
if not string.count(response, self.command_prompt):
return 0
for cmd in cmd_list:
t.write("%s\n" % cmd)
response = t.read_until(self.command_prompt, self.timeout)
if not string.count(response, self.command_prompt):
return 0
print response
return 1
if __name__ == '__main__':
basename = os.path.splitext(os.path.basename(sys.argv[0]))[0]
logname = os.environ.get("LOGNAME", os.environ.get("USERNAME"))
host = 'localhost'
import getopt
optlist, user_list = getopt.getopt(sys.argv[1:], 'c:f:h:')
usage = """
usage: %s [-h host] [-f cmdfile] [-c "command"] user1 user2 ...
-c command
-f command file
-h host (default: '%s')
Example: %s -c "echo $HOME" %s
""" % (basename, host, basename, logname)
if len(sys.argv) < 2:
print usage
sys.exit(1)
cmd_list = []
for (opt, optarg) in optlist:
if opt == '-f':
for r in open(optarg).readlines():
if string.rstrip(r):
cmd_list.append(r)
elif opt == '-c':
command = optarg
if command[0] == '"' and command[-1] == '"':
command = command[1:-1]
cmd_list.append(command)
elif opt == '-h':
host = optarg
autoTelnet = AutoTelnet(user_list, cmd_list, host=host)
Python的telnetlib允许用户轻松自动化对telnet服务器的访问,甚至可以从非Unix机器上进行访问。
作为popen()函数的替代方法,telnetlib可能是您能在sysadmin工具箱中找到的相当便捷的技术。
生产代码通常会更健壮,但是这个示例足以使任何人按正确的方向入门Telnet。