2018-06-06 Linux學習
遠程交互式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
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
[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]#
2018-06-06 Linux學習