答案是需要通过expect 来实现。
【注意】如果没有 expect ,需要预先安装
[tony@pd2 ~]$ yum info expect
Loaded plugins: fastestmirror
Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
Loading mirror speeds from cached hostfile
Available Packages
Name : expect
Arch : x86_64
Version : 5.45
Release : 14.el7_1
Size : 262 k
Repo : base/7/x86_64
Summary : A program-script interaction and testing utility
URL : http://expect.nist.gov/
License : Public Domain
Description : Expect is a tcl application for automating and testing
: interactive applications such as telnet, ftp, passwd, fsck,
: rlogin, tip, etc. Expect makes it easy for a script to
: control another program and interact with it.
:
: This package contains expect and some scripts that use it.
[tony@pd2 ~]$ whereis expect
expect:
[tony@pd2 ~]$
# 必须以root用户安装 expect
[root@pd2 tony]# whereis expect
[root@pd2 tony]# yum install -y expect
[root@pd2 kevin]# whereis expect
expect: /usr/bin/expect /usr/share/man/man1/expect.1.gz
-----------
# 写一个自动输入密码的脚本
[tony@pd2 ~]$ cat change2kevin
#!/usr/bin/expect
# 不论是在此脚本内自动输入密码还是在脚本外手工输入密码,至少要等待1秒
set timeout 1
# spawn将开启一个新的进程,也可以是ssh $user@$host {your_command}
# 只有先进入expect环境后才可执行spawn
spawn su kevin
# 判断上述进程(su kevin)的输出结果中是否有“password”的字符串(不区分大小写)。
# 若有则立即返回,否则就等待一段时间后返回,等待时长就是开头设置的1秒
expect "*password:"
# 向上面的进程(su kevin)发送字符串中的密码, 并且自动敲Enter健(\r)
send "kevin123456\r"
interact
---------------
# 验证一下, 从当前的 tony 用户切换到 kevin用户
[tony@pd2 ~]$ ./change2kevin
spawn su kevin
Password:
[kevin@pd2 kevin]$
成功切换用户!
【扩展】如何实现“输入用户名kevin,则自动切换到用户kevin?”
[tony@pd2 ~]$ vim ~/.bashrc # 编辑当前用户的bashrc脚本,在里面添加一行:alias kevin="./change2kevin"
[tony@pd2 ~]$ grep "alias kevin=" ~/.bashrc
alias kevin="./change2kevin"
[tony@pd2 ~]$ kevin # 直接使用刚才在bashrc中自定义的别名kevin,就能切换到kevin用户
spawn su kevin
Password:
[kevin@pd2 liangpeng]$ whoami