参考limodou

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import telnetlib

host = {}
host['ip']='127.0.0.1'
host['user']='user'
host['password']='password***'
host['commands']=['cd /home/xxxxx', 'ls -l --color=no']

def do(host):    
    tn = telnetlib.Telnet(host['ip'])
#    tn.set_debuglevel(2)    
    tn.read_until("login: ")    
    tn.write(host['user'] + "n")    
    tn.read_until("Password: ")    
    tn.write(host['password'] + "n")

#    tn.read_all()    

    for command in host['commands']:        
    	tn.write(command+'n')

    tn.write("exit")    
    print tn.read_all()

    print 'Finish!'

do(host)