一般我們使用 ssh 登入 linux 不外乎要輸入密碼,不用密碼的話就是 public key 了,
但如果不用以上兩種方式的話,就利用 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 ~]$

此時你不用輸入密碼。如果你希望登錄后做一些操作,然后退出,那也同樣可以做到。

Related posts 相關文章
xz liblzma 漏洞後門事件
More...
架設 VPN 服務 – WireGuard – 主打比 IPSec、OpenVPN 更快、安全
More...
ssh 到裝有 cygwin openssh 的 windows 主機卻出現 no kex alg 錯誤
More...
透過 SSH Tunnel 從 A SSH 連到 B
More...

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。