Original url: http://blog.sina.com.cn/s/blog_881c16550101nerl.html
原文地址:expect自动登陆后终端窗口大小变化的问题作者:yu_zhichun
expect脚本自动ssh登陆,当终端窗口发生变化时,默认expect不会将终端窗口大小改变的信号传送到远程的服务器上,因此在使用上会出现很不方便的地方,比如vim打开文件时出现串行,要是含有中文的文件可能根本无法编辑。
解决:捕获窗口大小改变的信号。
tcl写的expect脚本:
#!/usr/bin/env expect
#trap sigwinch spawned
trap {
set rows [stty rows]
set cols [stty columns]
stty rows $rows columns $cols < $spawn_out(slave,name)
} WINCH
set server xxx.xxx.xxx.xxx
set user root
set passwd *******
spawn ssh $user@$server
expect -re "password:"
send "${passwd}r"
expect -re "$"
interact
使用pexpect的python脚本:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
import struct, fcntl, os, sys, signal
import termios
import time
import datetime
# 此函数用来设置合适的窗口大小
def sigwinch_passthrough (sig, data):
# Check for buggy platforms (see pexpect.setwinsize()).
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
else:
TIOCGWINSZ = 1074295912 # assume
s = struct.pack ("HHHH", 0, 0, 0, 0)
a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
global global_pexpect_instance
global_pexpect_instance.setwinsize(a[0],a[1])
def main(host):
command = "ssh %s" % host
print command
p = pexpect.spawn(command)
try:
index = p.expect("Name or service not known",timeout=1)
if index == 0:
print 'host is wrong'
sys.exit(1)
except pexpect.TIMEOUT:
pass
try:
i = p.expect(['password:', 'continue connecting (yes/no)?', '[#$] '],timeout=5)
if i == 0:
p.sendline(password)
elif i == 1:
p.sendline("yes")
p.expect(['password:'])
p.sendline(password)
p.expect('[#$] ')
elif i == 2:
p.after
except pexpect.TIMEOUT:
print 'Connection timeout'
except pexpect.EOF:
print 'Connection exit'
p.close()
except Exception,e:
print "Connection close",e
global global_pexpect_instance
global_pexpect_instance = p
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
try:
p.interact()
sys.exit(0)
except:
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[1])elif i == 2: