meliae内存分析-基本用法
mkstemp、mktemp、TemporaryFile区别

python终端模拟工具pexpect

妙音 posted @ 2014年7月14日 22:28 in python , 4495 阅读
Pexpect是一个纯Python模块。 可以用来和ssh、ftp、passwd、telnet 等命令行程序进行自动交互。实现与命令行交互的自动化.
 
它提供了两个主要接口 run()函数和spawn类.
 
run()函数
run功能相对简单,只能实现简单交互
run(command,timeout=-1,withexitstatus=False,events=None,extra_args=None, logfile=None, cwd=None, env=None)
run运行命令,然后返回结果,与os.system类似.
示例
pexpect.run('ls -la')

# 返回值(输出,退出状态)
(command_output, exitstatus) = pexpect.run('ls -l /bin', withexitstatus=1)
 
spawn类
spawn功能比run强大,可以实现更复杂交互
class spawn 
    __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None)
timeout指定交互是等待的超时值
maxread设置read buffer大小. 每次pexpect尝试从TTY(Teletype终端)从读取的最大字节数.
searchwindowsize 指定了从输入缓冲区中进行模式匹配的位置,默认从开始匹配.
logfile 参数指定日志的记录位置
 
工作过程
# 第一步与终端建立连接
child = pexpect.spawn('scp foo user@example.com:.')
# 第二步等待终端返回匹配内容
child.expect('Password:')
# 第三步根据返回内容发送命令进行交互
child.sendline(mypassword)
 
pxssh类
pxssh是pexpect的派生类,用于建立ssh连接,比pexpect好用.
 
login()  建立到目标机器的ssh连接
logout() 释放该连接
prompt() 等待提示符,通常用于等待命令执行结束
 
工作过程与pexpect相同
# 初始化pxssh示例
s = pxssh.pxssh() 

hostname = raw_input('hostname: ') 
username = raw_input('username: ') 
password = getpass.getpass('password: ') 
# 建立ssh连接
s.login (hostname, username, password) 
# 发送命令到远程终端
s.sendline ('uptime') # run a command 
# 等待远程终端返回
s.prompt() # match the prompt 
# 打印匹配到的内容
print s.before  # print everything before the propt. 

# 发送命令到远程终端
s.sendline ('ls -l') 
# 等待远程终端返回
s.prompt() 
# 打印匹配到的内容
print s.before 

s.sendline ('df') 
s.prompt() 
print s.before 

# 释放ssh连接
s.logout() 
 
 
 
Avatar_small
Imamia Quran Academy 说:
2023年8月04日 07:06

Hi everyone, I really love your story. You have very useful information; I am from Imamia Quran Academy. Online Shia Quran Learning Center provides the best learning experience through its highly qualified teachers who are graduates in various fields of knowledge and make the lessons interesting. Shia Quran Madrasa is a convenient and reliable learning resource for people of all genders and ages making it the first choice of Shia Quran students.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter