百度空间 | 百度首页 
 
查看文章
 
Real ssh session using pexpect
2009-08-14 14:23
import pexpect

class sshSession:
def __init__(self, username, password, hostname, verbose=0, shell_promote='\$'):
self.username = username
self.password = password
self.hostname = hostname
self.child = None
self.verbose = verbose
self.shell_promote = shell_promote

def connect(self):
self.child = pexpect.spawn('ssh %s@%s' % (self.username,self.hostname))
index = self.child.expect(['assword:','authenticity'])
if index == 1:
self.child.sendline('yes')
self.child.expect('assword')
self.child.sendline(self.password)
index = self.child.expect(['please try again.',self.shell_promote])
if index == 0:
print 'wrong password'
return
elif index == 1:
if self.verbose:
print 'I am in'

def exec_command(self,command):
if not self.child:
print 'please first connect'
return
self.child.sendline(command)
self.child.readline()
self.child.expect(self.username)
result = self.child.before
self.child.expect(self.shell_promote)
return result
def close(self):
self.child.sendline('exit')
self.child.expect(pexpect.EOF)
if self.verbose:
print 'quit'

foo = sshSession('username','password','someserverwithsshopen')
foo.connect()
print foo.exec_command('echo hello')
foo.close()

类别:默认分类 | 浏览() | 评论 (0)
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu