当你不能把交互式的命令变成非交互式的命令时使用
# passwd user1 //交互式
# echo 123456 | passwd --stdin user1 //非交互式
#!/bin/bash
ip="172.16.70.251"
yum install expect -y
if grep 251 /etc/hosts
then
:
else
echo "$ip test.up.com">> /etc/hosts
fi
expect -c "
set timeout 300;
spawn ssh $ip; //spanwn 生成的意思
expect { // expect 捕获的意思
\"yes/no\" { send \"yes\n\"; exp_continue } //send 发送的意思
\"password:\" { send \"uplooking\n\";interact }
}
"
下面是安装expect并制作公钥使能够无交互式向172.16.70.251主机传送公钥,实现无交互式连接
#!/bin/bash
ip="172.16.70.251"
if [ -f /usr/bin/expect ];then
:
else
yum install expect -y
fi
if grep 251 /etc/hosts
then
:
else
echo "$ip test.up.com">> /etc/hosts
fi
rm -rf /root/.ssh/*
/usr/bin/expect <<EOF
set timeout 300
spawn ssh-keygen
expect "Enter file in which to save the key (/root/.ssh/id_rsa):"
send "\n"
expect "Enter passphrase (empty for no passphrase):"
send "\n"
expect "Enter same passphrase again:"
send "\n"
spawn ssh-copy-id 172.16.70.251
expect {
"yes/no" { send "yes\n"; exp_continue }
"root@172.16.70.251's password:" { send "qianfeng\n"}
}
expect eof //因为这里有 EOF<< EOF 所以expect eof必须写
EOF
ssh-add
ssh 172.16.70.251
和上面相似
#!/bin/bash
#expect实例
#author:wing
read -p "Your Name: " name
ip="172.16.70.251"
if [ -f /usr/bin/expect ];then
:
else
yum install expect -y
fi
if grep 251 /etc/hosts
then
:
else
echo "$ip test.up.com">> /etc/hosts
fi
#生成并拷贝ssh_key到远程机器
rm -rf /root/.ssh/*
/usr/bin/expect <<EOF
set timeout 30
spawn ssh-keygen
expect "Enter file in which to save the key (/root/.ssh/id_rsa):"
send "\n"
expect "Enter passphrase (empty for no passphrase):"
send "\n"
expect "Enter same passphrase again:"
send "\n"
spawn ssh-copy-id 172.16.70.251
expect {
"yes/no" { send "yes\n"; exp_continue }
"root@172.16.70.251's password:" { send "uplooking\n"}
}
expect eof
EOF
ssh-add
#远程登录并执行命令
/usr/bin/expect <<EOF
spawn ssh $ip
expect "test"
send "echo $name >> /var/ftp/1020name.txt\n"
send "不要动!!请等待清屏结束"
expect eof
EOF
clear
设置账户密码:
#!/usr/bin/expect
#set user [lindex $argv 0]
#set password [lindex $argv 1]
set user wing
set password wing
spawn passwd $user
expect "password:"
send "$password\r"
expect "password:"
send "$password\r"
expect eof
#!/usr/bin/expect -f
#set ip [lindex $argv 0 ]
#set dir [lindex $argv 1 ]
#set file [lindex $argv 2 ]
set ip 192.168.1.252
set download_file [lindex $argv 0 ]
set local_dir /
set timeout 20
spawn ftp $ip
expect "Name*"
send "robin\r"
expect "Password:*"
send "1\r"
expect "ftp>*"
send "lcd $local_dir\r"
expect "ftp>*"
send "get $download_file\r"
expect "ftp>"
send "quit\r"
expect eof
su到root后保持交互式:
# cat su1.sh
#!/usr/bin/expect
set timeout 300
spawn su - root
expect "Password:"
send "123\n"
interact
#cat su2.sh
#!/usr/bin/expect
set timeout 1
spawn su - user2 #生成命令
expect "Password:" #捕获关键字
send "123\n" #发送密码和回车
expect "$"
send "/wing_sh/aa/a.sh\n" #切换账户完毕执行其他命令或脚本
interact