在linux操作系統下,使用腳本自動化,一般由兩種方案,方案一:telnet+ftp,方案二:ssh+scp+expect。
以下主要使用ssh+scp+expect爲例進行說明使用方式。
第一步:安裝expect:yum -y install expect
第二步:驗證,執行expect是否正確
第三步:編寫腳本
ssh_exec(){ ip=$1 user=$2 passwd=$3 cmdstr=$4 /usr/bin/expect <<EOF set time 10 spawn ssh $user@$1 expect { "*yes/no" { send "yes\r"; exp_continue} "*password:" {send "$passwd\r"} } expect "*#" expect "*#" send "$cmdstr\r" expect "*#" send "exit\r" expect eof EOF } function scp_get () { local ip=$1 local user=$2 local passwd=$3 local src=$4 local dst=$5 [ -z "$ip" -o -z "$passwd" ] && return 1 /usr/bin/expect << EOF proc remote_exec {ip passwd src dst} { spawn scp \$user@\$ip:\$src \$dst exp_internal 0 expect { "yes/no" { send "yes\\r";exp_continue} "*password:" {send "\$passwd\\r"} } expect eof } remote_exec "$ip" "$user" "$passwd" "$src" "$dst" EOF } #從本地服務器複製到遠程服務器 function scp_put () { local ip=$1 local user=$2 local passwd=$3 local localfile=$4 local dst=$5 [ -z "$ip" -o -z "$passwd" ] && return 1 /usr/bin/expect << EOF proc remote_exec {ip passwd localfile dst} { spawn scp \$localfile \$user@\$ip:\$dst exp_internal 0 expect { "yes/no" { send "yes\\r";exp_continue} "*password:" {send "\$passwd\\r"} } expect eof } remote_exec "$ip" "$user" "$passwd" "$localfile" "$dst" EOF } ssh_exec 192.168.1.2 root 111111 'df -h' scp_get 192.168.1.2 root 111111 '/root/test.txt' '/opt/'
代碼說明:
第四步:對腳本授權,執行:chmod -R 755 script.sh
第五步:腳本執行,./script.sh (備註:shell+expect腳本,不能使用sh script.sh執行,只能採用./script.sh執行)