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

                分发系统介绍web

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

使用expect 能够实现文件传输和远程登陆vim

 


                 2、expect脚本远程登陆ssh

1. 安装expect:ide

yum install -y expectspa


QQ图片20180606234643.png

2.编写expect脚本:orm

vim /usr/local/sbin/1.expectthree

 

内容:图片

 #! /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
ip

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

3.修改脚本权限:

chmod a+x one.expect


执行命令: ./one.expect

QQ图片20180607002913.png

 


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

                 3、 expect脚本远程执行命令

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

1.脚本内容:

#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh $user@192.168.136.134

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

成功登陆,并完成建立命令最后退出。


                   4、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

相关文章
相关标签/搜索