文档课题:expect作用测试—避免scp中途输密码.
系统:centos 7.9
1、安装expect
在生产环境中scp和ssh时使用免密匙登录,会给安全带来隐患,所以引入expect功能.
--查系统是否安装expect
[root@leo-oracle-11g:~]# rpm -qa | grep expect
--安装expect
[root@leo-oracle-11g:/etc/yum.repos.d]# yum install -y expect
[root@leo-oracle-11g:/etc/yum.repos.d]# rpm -qa | grep expect
expect-5.45-14.el7_1.x86_64
2、简单示例
[root@leo-oracle-11g:~]# vi expect.sh
#!/usr/bin/expect
set timeout 20
spawn ssh root@192.168.133.116
expect "root"
send "rootrootn"
interact
说明:
第一行指定执行模式,平时shell是用#!/bin/bash,此处采用#!/usr/bin/expect;
第二行设置响应时间,若脚本执行时间超过该设置将不执行;
spawn:表示需要执行的shell脚本;
expect捕获执行shell后系统返回的提示内容,""表示提示信息是否包含引号中内容;
send:如果expect检测到双引号中内容,则将send后的信息进行发送并执行回车(n);
interact:结束expect会话,虽然可以继续输入,但不会返回终端.
测试:
[root@leo-oracle-11g:~]# hostname
leo-oracle-11g
[root@leo-oracle-11g:~]# ./expect.sh
spawn ssh root@192.168.133.116
root@192.168.133.116's password:
Last login: Tue May 23 18:32:14 2023 from 192.168.133.110
[root@leo-mysql5718 ~]# hostname
leo-mysql5718
说明:如上所示,执行expect.sh后,成功登录到192.168.133.116主机,期间并没有被要求输入密码.
3、工作案例
[root@leo-oracle-11g:~]# vi scp.sh
#!/usr/bin/expect
set timeout 20
set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set file [lindex $argv 3]
set dir [lindex $argv 4]
spawn scp $file $user@$ip:$dir
expect {
"*password:*" {
set timeout 1000
send "$passwdr"
exp_continue
}
"*es/no)?*" {
send "yesr"
exp_continue
}
timeout {
puts "connect is timeout"
exit 3
}
}
[root@leo-oracle-11g:~]# chmod u+x scp.sh
[root@leo-oracle-11g:~]# nohup ./scp.sh 192.168.133.116 root password /root/mysql-5.7.18-linux-glibc2.5-x86_64.tar.gz /root &
--验证
[root@leo-mysql5718 ~]# ll
total 639104
-rw-------. 1 root root 2248 May 23 16:11 anaconda-ks.cfg
-rw-r--r--. 1 root root 2341 May 23 16:26 initial-setup-ks.cfg
-rw-r--r--. 1 root root 654430368 May 24 11:38 mysql-5.7.18-linux-glibc2.5-x86_64.tar.gz
-rw-r--r--. 1 root root 0 May 24 11:35 test.txt
说明:文件成功传输到主机leo-mysql5718端,期间并未被要求输入密码.
参考文档:https://blog.csdn.net/zfw_666666/article/details/124670057
服务器租用托管,机房租用托管,主机租用托管,https://www.e1idc.com