分发系统介绍、expect脚本远程登录、登录执行命令后退出、脚本传递参数

                分发系统介绍

shell项目-分发系统-expect (expect也是一种脚本语言)

使用expect 可以实现文件传输和远程登录


                 二、expect脚本远程登录

1. 安装expect:

yum install -y expect


QQ图片20180606234643.png

2.编写expect脚本:

vim /usr/local/sbin/1.expect

内容:

 #! /usr/bin/expect
set host "192.168.136.134"  //设置变量host
set passwd "123456"           //设置变量passwd
spawn ssh root@$host
expect {                   
"yes/no" { send "yes\r"; exp_continue}     //一般我们在远程登陆一台机器的时候会在输入密码的 时候提示“yes/no“关键字再输入yes后才可以输入密码。这里首先是截取”“yes/no”关键字然后执行send“yes\r”(\r表示回程)
"assword:" { send "$passwd\r" }
}
interact

(interact:表示登录远程机器后保留在登录的机器。如果不加这个interact,则登录后立马退出。或者使用 expect eof 这个命令,则会在登录机器后的2-3s后退出)

3.修改脚本权限:

chmod a+x one.expect


执行命令: ./one.expect

QQ图片20180607002913.png


注意:在脚本中要注意的是(1)符号的大小写(2)在expect{}的“{ ”要和expect有空格

                 三、 expect脚本远程执行命令

自动远程登录后,执行命令并退出

1.脚本内容:

#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh [email protected]

expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}

  //登录以后
expect "]*"   //当遇到字符“]*”,一般登录以后的都是']#'。普通用户为']$'  ,此处']*'表示通配  QQ图片20180607003608.png

send "touch /tmp/12.txt\r"
expect "]*"
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
send "exit\r"

 QQ图片20180607003900.png


2.编写完脚本,修改脚本权限:

chmod a+x two.expect


3.执行脚本,判断是否会在登陆后执行完命令退出登录

./two.expect

QQ图片20180607004253.png

成功登录,并完成创建命令最后退出。


                   四、expect脚本传递参数


  1.传递参数脚本内容:
#!/usr/bin/expect

set user [lindex $argv 0]   //设定第一个传递参数的格式
set host [lindex $argv 1]
set passwd "123456"
set cm [lindex $argv 2]
spawn ssh $user@$host

expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"



2.编写完脚本,修改脚本权限:

chmod a+x three.expect


3.执行脚本 并传递参数 ./three.expect root 192.168.136.134 w;ps

表示传递用户名:root ;登录主机ip和执行的命令w和ps




猜你喜欢

转载自blog.51cto.com/13589255/2125784
今日推荐