介紹:使用命令執行腳本,免鍵入密碼直接ssh連接服務器
環境:MacOS
軟件:expect(brew安裝sshpass提示有安全問題,所以不使用sshpass)
1.安裝expect
brew install expect
2.建立.sh腳本
touch login.sh
3.編輯腳本
#!/usr/bin/expect -f // 路徑查看命令:which expect
set timeout 3
spawn ssh [email protected]
expect "*password*" // 期待匹配‘*password*’字符串
send "LD7SsssyGe19jg7VM\r" // 鍵入密碼,並回車
interact // 允許用戶與命令號交互
4.添加腳本執行權限並測試
chmod a+x login.sh
5.當前用戶目錄下建立.bash_profile文件
vi ~/.bash_profile
說明:當前目錄的.bash_profile會在shell客戶端啓動初始化
6.編輯.bash_profile
alias lg='/Users/xdc/Work/script/shell/login.sh'
作用:添加了命令“lg”,該命令用於執行後面的腳本
7.使命令生效
source ~/.bash_profile
8.執行lg命令測試
問題:
關閉terminal客戶端後,lg命令不生效,必須source一下才能生效:
查看默認的shell客戶端
echo $SHELL
輸出結果:/bin/zsh,說明zsh爲默認shell,terminal init的時候並不會執行~/.bash_profile
解決辦法:
編輯.zshrc文件,該文件爲zsh客戶端啓動加載的文件。裏面添加重新加載bash文件的命令,也可以直接添加"aligs lg..."這段代碼
source .bash_profile