2018-06-06 Linux学习

20.27 分发系统介绍

远程交互式ssh登陆,远程执行命令,配置服务。

20.28 expect脚本远程登录

yum install -y expect
自动远程登录

#! /usr/bin/expect
set host "192.168.133.132"
set passwd "123456"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue }
"password:" { send "$passwd\r" }
}
interact

操作过程

[root@linux-01 sbin]# vim 1.expect

#!/usr/bin/expect
set host "192.168.106.165"
set passwd "356666"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue }
"password:" { send "$passwd\r" }
}
interact

[root@linux-01 sbin]# chmod a+x 1.expect
[root@linux-01 sbin]# ./1.expect
spawn ssh [email protected]
The authenticity of host '192.168.106.165 (192.168.106.165)' can't be established.
ECDSA key fingerprint is SHA256:g28ZF++YHmMwZQb9yLYbyPjGGZIeHU/T062FZHjtRhk.
ECDSA key fingerprint is MD5:2e:db:58:71:93:d8:09:a1:d9:bf:ad:2a:60:ba:b2:a6.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.106.165' (ECDSA) to the list of known hosts.
[email protected]'s password:
Last login: Tue Apr 24 15:57:54 2018 from 192.168.106.1
[root@linux-02 ~]#

20.29 expect脚本远程执行命令

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

#!/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 "]"
send "touch /tmp/12.txt\r"
expect "]
"
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
send "exit\r"

操作过程

[root@linux-01 sbin]# vim 2.expect

#!/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 "]"
send "touch /tmp/12.txt\r"
expect "]
"
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
send "exit\r"

[root@linux-01 sbin]# chmod a+x 2.expect 

[root@linux-01 sbin]# ./2.expect 
spawn ssh [email protected]
[email protected]'s password: 
Last login: Tue Apr 24 16:13:17 2018 from 192.168.106.160
[root@linux-02 ~]# touch /tmp/12.txt
[root@linux-02 ~]# echo 1212 > /tmp/12.txt
[root@linux-02 ~]# [root@linux-01 sbin]#

20.30 expect脚本传递参数

传递参数

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

操作过程

[root@linux-01 sbin]# vim 3.expect
写入上面的传递参数 内容

[root@linux-01 sbin]# chmod a+x 3.expect 

[root@linux-01 sbin]# ./3.expect root 192.168.106.165 ls
spawn ssh [email protected]
[email protected]'s password: 
Last login: Tue Apr 24 16:24:52 2018 from 192.168.106.160
[root@linux-02 ~]# ls
anaconda-ks.cfg  mysql-5.6.39-linux-glibc2.12-x86_64.tar.gz  zabbix-release-3.4-2.el7.noarch.rpm
[root@linux-02 ~]# [root@linux-01 sbin]# 

猜你喜欢

转载自blog.51cto.com/9298822/2125715