python pexpect pxssh copy_Python学习笔记4-pexpect模块,pxssh

今天试了下自动登录,遇到了点问题:

#!/usr/bin/python

# Filename: auto_ssh.py

import pexpect

import pxssh

def auto_ssh_cmd(ip,username,password,command,port=22):

try:

remote = pxssh.pxssh()

remote.login(ip,username,password)

remote.sendline(command)

remote.prompt()

print remote.before

remote.logout()

except pxssh.ExceptionPxssh, e:

print "pxssh failed on login."

print str(e)

报错:

$ python auto_ssh.py

Traceback (most recent call last):

File "auto_ssh.py", line 26, in

auto_ssh_cmd(ip_ad,user,passw,cmd)

File "auto_ssh.py", line 17, in auto_ssh_cmd

remote.login(ip,username,password)

File "/usr/lib/python2.7/dist-packages/pxssh.py", line 243, in login

if not self.synch_original_prompt():

File "/usr/lib/python2.7/dist-packages/pxssh.py", line 134, in synch_original_prompt

self.read_nonblocking(size=10000,timeout=1) # GAS: Clear out the cache before getting the prompt

File "/usr/lib/python2.7/dist-packages/pexpect.py", line 824, in read_nonblocking

raise TIMEOUT ('Timeout exceeded in read_nonblocking().')

google了一下,找到了一个解决方法:

修改site-packages/pxssh.py

在def synch_original_prompt (self):方法下第一个self.read_nonblocking(size=10000,timeout=1)前面增加两行代码

self.sendline()

time.sleep(0.5)

按照提示的修改,果然可以正常工作了。。。。

在chinaunix上面找到一个解释:

I don't know if anyone ever got back to you with a fix, but for me the

fix was really simple.

I just added a self.sendline() and a time.sleep(0.5) right before the

first read_nonblocking() call within synch_original_prompt

The reason is that you have to have stuff in the buffer in order to

read it. In the case that they programmed for originally,

**something** exists in their prompt (probably a space) after the $ or

#. In my case (and probably yours) the last thing on the prompt

**is** the $ or #, causing the buffer to be non-existent when the

first read_nonblocking() happens. So all we do is put something there

before the read.

Why not just get rid of the first read since it is just "clearing the

buffer" anyway? Because then, although it would now work for us, it

would no longer work for the original programmers.

想写一个脚本,可以批量deploy环境到多台服务器上。。。

用pxssh,可是发现登录到远端服务器后,不能后台执行命令。。而布署环境的时间较长,如果block的话,整体时间过长。怎么可以后台执行呢?

#!/usr/bin/python

import pxssh

host = 'hostname'

user = 'user'

passwd = 'passwd'

myssh = pxssh.pxssh();

myssh.login(host,user,passwd)

myssh.prompt()

myssh.sendline('nohup ls -l &')

myssh.prompt()

myssh.logout()

上面的代码不能工作。。。T_T

----有人建议试用fabric。。做个记号先,学习来再写上来。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值