標籤:linux 密碼 認證 password expect
在實際生產使用中,比如執行大量操作時,我們不想建立ssh認證,需要使用到密碼登入或者連結,此時可以使用expect來操作自動添加password:
在centos系統上expect預設是沒有安裝的,所以首先應先安裝expect:
yum install expect -y
建立expect指令碼:
[[email protected] script]# cat ssh_203.exp#!/usr/bin/env expectset timeout 5set remote_ip "192.168.1.203"set passwd "hh123456"spawn ssh [email protected]$remote_ipexpect { "(yes/no)?" {send "yes\n";exp_continue} "password:" {send "$passwd\r"}}expect "*#"send "cd /data/script && touch mxd{1..10}\r"interact
interact的作用是讓以上登入後留在遠程主機控制台上,這樣不會退出遠程主機,僅用於ssh登入。
執行指令碼:
[[email protected] script]# ./ssh_203.exp (或者/usr/bin/expect ssh_203.exp)
以下為使用scp傳輸一個檔案到遠程主機:
cat 22.sh#!/usr/bin/env expectset timeout 5set remote_ip "192.168.1.203"set passwd "hh123456"spawn scp -rp /data/script/ssh_203.sh [email protected]$remote_ip:/data/script/expect { "(yes/no)?" {send "yes\r";exp_continue} "password:" {send "$passwd\r" }}expect eof
expect eof 表示執行完成命令後退出遠程主機
timeout則表示串連異常時等待的逾時時間
以下為將檔案傳輸帶遠程主機並執行:
cat 33.sh#!/usr/bin/env expectset timeout 5set remote_ip "192.168.1.203"set passwd "hh123456"spawn scp -rp /data/script/ssh_203.sh [email protected]$remote_ip:/data/script/expect "password:"send $passwd\rspawn ssh [email protected]$remote_ip "sh /data/script/ssh_203.sh"expect "password:"send $passwd\rexpect eof
linux中使用expect實現自動登入