expect使用问题,跪求指导!!!!
以下是我写的一个测试用的脚本:
#!/usr/bin/expect -f
set passwd
set ipaddress
set timeout 10
spawn ssh -q alne@$ipaddress
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$passwd\r" }
}
expect "\$"
send "uptime \r"
send "exit \r"
expect eof
exit
脚本执行到登陆远程机器以后就会停住,
和set timeout 设置的时间有关系,我要是设置10秒,他就会等10秒才会执行 send后的命令,设置100秒他就等100秒才执行send命令。
没用过啊,痛苦啊,这是怎么回事,跪求回复啊 #!/usr/bin/env python
"""
This runs a command on a remote host using SSH. At the prompts enter hostname,
user, password and the command.
"""
import pexpect
import getpass, os
#user: ssh 主机的用户名
#host:ssh 主机的域名
#password:ssh 主机的密码
#command:即将在远端 ssh 主机上运行的命令
def ssh_command (user, host, password, command):
"""
This runs a command on the remote host. This could also be done with the
pxssh class, but this demonstrates what that class does at a simpler level.
This returns a pexpect.spawn object. This handles the case when you try to
connect to a new host and ssh asks you if you want to accept the public key
fingerprint and continue connecting.
"""
ssh_newkey = 'Are you sure you want to continue connecting'
# 为 ssh 命令生成一个 spawn 类的子程序对象.
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
i = child.expect()
# 如果登录超时,打印出错信息,并退出.
if i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login. Here is what SSH said:'
print child.before, child.after
return None
# 如果 ssh 没有 public key,接受它.
if i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
child.expect ('password: ')
i = child.expect()
if i == 0: # Timeout
print 'ERROR!'
print 'SSH could not login. Here is what SSH said:'
print child.before, child.after
return None
# 输入密码.
child.sendline(password)
return child
def main ():
# 获得用户指定 ssh 主机域名.
host = raw_input('Hostname: ')
# 获得用户指定 ssh 主机用户名.
user = raw_input('User: ')
# 获得用户指定 ssh 主机密码.
password = getpass.getpass()
# 获得用户指定 ssh 主机上即将运行的命令.
command = raw_input('Enter the command: ')
child = ssh_command (user, host, password, command)
# 匹配 pexpect.EOF
child.expect(pexpect.EOF)
# 输出命令结果.
print child.before
if __name__ == '__main__':
try:
main()
except Exception, e:
print str(e)
traceback.print_exc()
os._exit(1)
看下pexpect也能实现。
参考URL http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect2/ #!/usr/bin/expect -f
set passwd
set ipaddress
set timeout 10
spawn ssh -q alne@$ipaddress
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$passwd\r" }
}
set timeout 1 # 这里重新定义timeout 时间就可以了,笨办法
expect "\$"
send "uptime \r"
send "exit \r"
expect eof
exit 同问坐等!http://www.mohuanshouji2shaniuguilai.com 回复 2# steveneast
可是下面在执行命令的时候等待时间是按上面的10秒还是下面的1秒呢? settimeout-1 只有在成功expect ,就会send 。 回复 5# hongjie7456
还是不行 #!/usr/local/bin/expect -f
set passwd
set ipaddress
set timeout 10
spawn ssh -l bizcard $ipaddress
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$passwd\r" }
}
expect "*\$"
send "uptime\r"
expect "*\$"
send "exit\r"
expect eof
exit
试试这个,应该是没问题了。 超时时间设置短一点不可以么? 回复 9# xiaodylan
那样的话如果执行大点的脚本或是安装软件的话就会因为超时自动断开