linux中使用expect實現自動登入

來源:互聯網
上載者:User

標籤: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實現自動登入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.