计算机小白,希望所学知识能够帮助你
自动交互的方法
1.查看命令,看看有没有选项用来实现自动交互的。
[root@dbserver02 ~]# echo “123” | passwd --stdin a1
Changing password for user a1.
passwd: all authentication tokens updated successfully.
2.输入重定向
Passwd u1 < /tmp/a.txt
3.Here document
[root@LVM ~]# passwd a1 << eof
123
123
eof
Changing password for user a1.
New password: BAD PASSWORD: it is WAY too short
BAD PASSWORD: is too simple
Retype new password: passwd: all authentication tokens updated successfully.
4.用expect来实现
安装expect
[root@LVM Packages]# rpm -ivh expect-5.44.1.15-5.el6_4.x86_64.rpm tcl-devel-8.5.7-6.el6.x86_64.rpm tcl-8.5.7-6.el6.x86_64.rpm
warning: expect-5.44.1.15-5.el6_4.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY
Preparing… ########################################### [100%]
1:tcl ########################################### [ 33%]
2:expect ########################################### [ 67%]
3:tcl-devel ########################################### [100%]
expect 完成自动交互的任务
[root@mysqlserver01 scripts]# rpm -qa | grep “expect”
expect-5.44.1.15-5.el6_4.x86_64
expect内部命令:
spawn: 后面加上需要执行的shell命令,比如说spawn ssh root@172.16.1.1
expect: 只有spawn 执行的命令结果才会被expect 捕捉到,因为spawn 会启
动一个进程,只有这个进程的相关信息才会被捕捉到。
send:send 会将expect 脚本中需要的信息发送给spawn 启动的那个进程
send_user: 只在屏幕显示,不送给spawn 启动的那个进程,相当于echo
定义变量:
set
例如:
set passwd “mypasswd”
set timeout 60
a
r
g
c
参
数
个
数
相
当
于
b
a
s
h
的
argc 参数个数 相当于bash的
argc参数个数相当于bash的#
a
r
g
v
数
组
,
存
放
所
有
参
数
类
似
于
b
a
s
h
的
argv 数组,存放所有参数 类似于bash的
argv数组,存放所有参数类似于bash的@
如果需要在shell脚本中嵌套expect代码,就要使用expect -c “expect代码”
例如:
expect -c "
spawn ssh
u
s
e
r
n
a
m
e
@
user_name@
username@ip_addr df -P
expect {
“*(yes/no)?” {send “yes\r” ; exp_continue}
“*password:” {send “$user_pwd\r” ; exp_continue}
}
"
##################################################
#!/usr/bin/expect
set timeout 60
set ip_addr [lindex $argv 0]
set username [lindex $argv 1]
set user_pwd [lindex $argv 2]
set cmd_line [lindex $argv 3]
if {$argc != 4} {
send_user “usage: ./auto_login ip username password command\n”
exit
}
spawn ssh u s e r n a m e @ username@ username@ip_addr $cmd_line
expect {
“(yes/no)?” {
send “yes\r”
exp_continue
}
"password:" {
send "$user_pwd\r"
exp_continue
}
}
总结:
自动交互的方法:
1、查找帮助,看有没有选项实现自动交互
2、用输入重定向能不能实现
3、用here document能不能实现
4、用expect能不能实现