您的位置:首页 > 其它

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

2017-11-30 11:45 891 查看

分发系统介绍

expect可以让我们实现自动登录远程机器,并且可以实现自动远程执行命令。当然若是使用不带密码的密钥验证同样可以实现自动登录和自动远程执行命令。但当不能使用密钥验证的时候,我们就没有办法了。所以,这时候只要知道对方机器的账号和密码就可以通过expect脚本实现登录和远程命令。


expect脚本远程登录

安装:
[root@centos7 mon]# yum install -y expect



[root@centos7 shares]# vi login.expect
#! /usr/bin/expect
set host "192.168.3.83"
#连接到主机192.168.3.83
set passwd "123456"
#密码
spawn ssh root@$host
#spawn调用shell命令ssh(登录),“set host”和“set passwd”为expect定义的两个变量
expect {
"yes/no" { send "yes\r"; exp_continue}
#ssh首次远程登录一台主机是会提示yes/no;"\r“表示回车
"assword:" { send "$passwd\r" }
#密码
}
interact
#interact的作用是停留在远程机器上,不退出
#expect脚本结束符号:expect eof——执行结束后暂停几秒钟后退出
#如果不加任何结束符号,命令执行完后马上退出

执行:
chmod +x login.expect
[root@centos7 shares]# ./login.expect
spawn ssh root@192.168.3.83
root@192.168.3.83's password:
Last login: Thu Nov 30 11:36:38 2017 from 192.168.3.74

登录到了192.168.3.83上

expect脚本远程执行命令

执行完成就退出了
vim 2.expect
#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh $user@192.168.3.83

expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]"
#匹配到“]”时执行下面的命令
send "touch /tmp/12.txt\r"
expect "]"
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
send "exit\r"

expect脚本传递参数

1、[root@centos7 shares]# vim 3.expect

#!/usr/bin/expect
#调用expect内置变量:“[lindex $argv 0]”、“[lindex $argv 1]”、“[lindex $argv 2]”
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、[root@centos7 shares]# chmod +x 3.expect
[root@centos7 shares]# ./3.expect root 192.168.3.83 ls;w
spawn ssh root@192.168.3.83
root@192.168.3.83's password:
Last login: Thu Nov 30 11:42:28 2017 from 192.168.3.74
[root@test ~]# 11:44:28 up 1 day, 9:49, 2 users, load average: 0.11, 0.07, 0.06
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 192.168.3.81 Tue17 22:52 0.29s 0.29s -bash
root pts/1 192.168.3.81 Tue10 4.00s 1.20s 0.01s w
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  expect
相关文章推荐