ssh 搭配 expect 讓登入時可以自動化
作者: cross 日期: 2007-11-28 13:01
但如果不用以上兩種方式的話,就利用 expect 作互動方式,
有個參考範例如下
Quote: http://bash.cyberciti.biz/security/sshlogin.exp.php
#!/usr/bin/expect -f
# Expect script to supply root/admin password for remote ssh server
# and execute command.
# This script needs three argument to(s) connect to remote server:
# password = Password of remote UNIX server, for root user.
# ipaddr = IP Addreess of remote UNIX server, no hostname
# scriptname = Path to remote script which will execute on remote server
# For example:
# ./sshlogin.exp password 192.168.1.11 who
# ------------------------------------------------------------------------
# Copyright (c) 2004 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# ----------------------------------------------------------------------
# set Variables
set password [lrange $argv 0 0]
set ipaddr [lrange $argv 1 1]
set scriptname [lrange $argv 2 2]
set arg1 [lrange $argv 3 3]
set timeout -1
# now connect to remote UNIX box (ipaddr) with given script to execute
spawn ssh root@$ipaddr $scriptname $arg1
match_max 100000
# Look for passwod prompt
expect "*?assword:*" # < 遇到提示的相關字串
# Send password aka $password
send -- "$password " # < 遇到提示的相關字串後,就輸入密碼變數內的值
# send blank line ( ) to make sure we get back to gui
send -- " "
expect eof
它的用法 ./sshlogin.exp 密碼 遠端主機 執行的指令 額外的
比如執行 ./sshlogin.exe 123456 192.168.1.93 whoami
就會顯示 root
而 ./sshlogin.exe 123456 192.168.1.93 touch 111
在 root 家目錄底下就會多了 111 這個檔案,111 這個是給 $arg1 變數
假如要將 111 更名為 222
就要修改一下
增加 set arg2 [lrange $argv 4 4]
改 spawn ssh root@$ipaddr $scriptname $arg1 為 spawn ssh root@$ipaddr $scriptname $arg1 $arg2
然後執行 ./sshlogin.exe 123456 192.168.1.93 mv 111 222
2007/12/06 發現一有趣的訊息
Quote: http://mlsx.xplore.cn/read.php/298.htm
autoexpect:這個腳本將根据自身在運行時用戶的操作而生成一個expect腳本。它的功能某種程度上類似于在Emacs編輯器的鍵盤宏工具。一個自動創建的腳本可能是創建自己定制腳本的好的開始。比如我要使用ssh登錄一台机器,你可以這樣做:
[mlsx@wgzhao ~]$ autoexpect -f ssh.exp ssh mlsx@localhost
autoexpect started, file is ssh.exp
mlsx@localhost's password:
Last login: Thu Apr 13 17:04:23 2006 from localhost.localdomain
[mlsx@wgzhao ~]$你所有的操作都記錄再ssh.exp文件里面,下次如果你還想用同樣的登錄相同的机器,那你可以這樣做:
[mlsx@wgzhao ~]$ ./ssh.exp
spawn ssh mlsx@localhost
mlsx@localhost's password:
Last login: Thu Apr 13 17:04:56 2006 from localhost.localdomain
[mlsx@wgzhao ~]$此時你不用輸入密碼。如果你希望登錄后做一些操作,然后退出,那也同樣可以做到。
上一篇
返回
下一篇
標籤:




如何在ssh登入主機遠端主機時不要有key的檢查 (2012-01-03 09:16)
設定ssh連線30分鐘後沒有動作就自動斷線 (2011-12-26 23:59)
把 ssh public key 遠端複製過去 (另一種方式) (2011-10-26 14:32)
ssh搭配pam_tally2讓使用者登入,幾次失敗就鎖定時間,過了才可再次登入 (2011-04-28 14:58)
SSH 幾項安全性設置 (2011-04-27 00:19)
防ssh的暴力式攻擊-DenyHosts (2011-04-17 23:45)
怎麼在ssh console底下刪除特殊字元的檔案 (2010-02-22 19:28)
SSH 使用技巧 - 縮短名稱 (2009-04-21 21:04)
sudo 讓一般使用者有 Root 權限 (Part II) (2008-08-04 22:19)