Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux expect 自動交互腳本實戰:無密碼切換 root 執行掃毒命令

編輯:Linux 系統常見問題解答

expect 是自動化交互式程序(ssh、su、ftp、passwd 等)的利器。本文演示安裝 expect、編寫腳本實現「普通用戶調用 → 自動 su root → 執行卡巴斯基掃毒 → 返回結果」的完整流程。

1. 安裝 expect

yum install -y expect

2. 核心腳本 verify_virus

#!/usr/bin/expect -f
# 自動 su root 執行掃毒並返回感染狀態

set file [lindex $argv 0]
spawn su -c "/opt/kaspersky/kav4fs/bin/kav4fs-control --scan-file $file" root

expect {
    "*Password:" { send "RootPassword\r" }
}
interact
  • spawn 啟動子進程
  • expect 匹配提示符
  • send 發送密碼含回車 \r
  • interact 交還控制權(此處用於捕獲輸出)

3. 封裝 Shell 調用腳本

#!/bin/bash
file=$1
if [[ ! -e $file ]]; then
    echo "no"; exit 0
fi
infected=$(./verify_virus "$file" | grep "Infected" | grep "0")
if (($?)); then
    echo "yes"   # 檢測到病毒
else
    echo "no"    # 無病毒
fi

4. 關鍵語法速查

命令說明
spawn cmd啟動進程,建立交互通道
expect "pattern"等待輸出匹配模式
send "string\r"發送字符串(含回車)
exp_continue匹配後繼續期待下一模式
interact將控制權交給用戶/腳本繼續讀取輸出
set timeout 秒設置期待超時(默認 10s)
set var [lindex $argv n]獲取命令行參數

應用場景擴展

  • 批量 SSH 執行命令(配合密鑰免密更佳)
  • 自動化 passwd 修改密碼
  • FTP/SFTP 自動上傳下載
  • 設備配置下發(Telnet/SSH 登錄網絡設備)

安全提示

  • 腳本中明文密碼風險極高,生產環境請:
    • 使用 SSH 密鑰替代密碼交互
    • 或將密碼存入加密文件,運行時解密讀取
    • 限制腳本權限 chmod 700,僅擁有者可讀執行

掌握 expect,讓一切交互式操作可腳本化、可自動化、可編排。

Copyright © Windows教程網 All Rights Reserved