今天试了下自动登录,遇到了点问题:
#!/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 <module> 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().')
修改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()
----有人建议试用fabric。。做个记号先,学习来再写上来。。。