答案是需要通過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
好了,就寫到這裏,看官們覺得漲知識了,請爲本文點個贊 ^_^