如何在linux shell脚本中自动输入密码.

答案是需要通过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]$

成功切换用户!

另外,如果临时需要从本地通过ssh登录到远程机器的需求,也可以写一个类似的脚本:

[tony@pd2 ~]$ cat to_pd4.sh

#!/usr/bin/expect
set timeout 1
spawn ssh tony@pd4
send "yes\r"
expect "*password:"
send "hello\r"
interact

[tony@pd2 ~]$ ./to_pd4.sh    # 测试一下
spawn ssh tony@pd4
yes
tony@pd4's password: 
Last login: Thu Apr  9 17:45:41 2020 from bd01
[tony@pd4 ~]$ 

从结果可知,无需手动输入ssh密码,成功登入远程机器 ^_^

 

【扩展】如何实现“输入用户名kevin,则自动切换到用户kevin?”

[tony@pd2 ~]$ vim ~/.bashrc     # 编辑当前用户的bashrc脚本,在里面添加一行:alias kevin="./change2kevin"

[tony@pd2 ~]$ grep "alias kevin=" ~/.bashrc 

alias kevin="./change2kevin"

[tony@pd2 ~]$ source ~/.bashrc
[tony@pd2 ~]$ kevin        #  直接使用刚才在bashrc中自定义的别名kevin,就能切换到kevin用户
spawn su kevin
Password: 
[kevin@pd2 liangpeng]$ whoami

kevin

好了,就写到这里,看官们觉得涨知识了,请为本文点个赞 ^_^

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章