用Linux expect 实现远程自动登录服务器,并操作Linux命令

#!/bin/bash
############################
#去121服务器执行数据库脚本
############################
#Linux 自带expect 工具,可以自行安装
# \r 表示回车确认,得有
ServerUserPwd1="密码\r"
expect <<!
#设置远程连接的超时时间,-1 表示不会超时
set timeout -1
#远程连接 22 端口 服务器 10.0.18.1111
spawn ssh -p 22 10.0.18.121
expect "*password:"
#发送密码
send $ServerUserPwd1
#如果要操作远程操作Linux命令,expect "*]#" 表示命令的开始
expect "*]#"
#命令执行
#切换用户
send "su - oracle\r"
#用plsql执行写好的sql脚本,日记输出到Linux自带的 nohup 
send "nohup sqlplus bto_c2/oss @/opt/oracle/db11/sync_categorydtl_sql/exec_t.sql &\r"
#退出之前切换的用户
send "logout\r"
#操作完了以后退出远程
send "exit\r"
#命令结束表示
expect "*]#"
expect eof
!
posted @ 2017-11-21 16:35  小和尚的木鱼  阅读(1709)  评论(0编辑  收藏  举报