caboのIT系Tipsの情報まとめ

インフラエンジニアなのでそれに関連したIT関連の記事や技術情報をメインに扱います。また、趣味のアウトドアや写真(主に風景)が好きなのでそちらもネタがあれば載せようと思います。

expectを利用してssh処理を自動化してリモートコマンドを実行

Linuxのexpectのコマンドサンプルになります。

制御サーバから各々のサーバにコマンドを実行したかったのですがキー交換がシステム制約上できなかったので、簡単にラップ用のSHELLを作成しました。

JOBサーバを立てられないのでいまであれば、Ansibleとかするんでしょうが。。

 

 

argv 説明 
0 Host 10.5.10.101
1 LoginUser oracle
2 PW oracle
3 Command:実行コマンド、”くくりが必要 ls -al

# cat Comm_exe.sh

 

#!/usr/bin/expect
 
# Logfile
log_file /var/log/Comm_exe.log
 
# Environment
set Host [lindex $argv 0]
set LoginUser [lindex $argv 1]
set PW [lindex $argv 2]
set Command [lindex $argv 3]
set Prompt "\[#$%>\]"
 
# Command TimeOUt
set timeout 5
 
spawn env LANG=C /usr/bin/ssh ${LoginUser}@${Host}
expect {
    "(yes/no)?" {
        send "yes\n"
        exp_continue
    }
    -re "password:" {
        send -- "${PW}\n"
    }
}
 
expect {
    -glob "${Prompt}" {
        send "uname -n;id\n"
    }
}
 
expect {
    -glob "${Prompt}" {
        send "${Command}\n"
    }
}
 
expect {
    -regexp "\n.*\r" {
        send "exit\n"
        exit 0
    }
}

 

# ./Comm_exe.sh 10.5.10.101 oracle oracle "ls -al"

spawn env LANG=C /usr/bin/ssh oracle@10.5.10.101
oracle@10.5.10.101's password:
Last login: Mon Jan 14 18:30:54 2019 from control-serv
[oracle@rac1111 ~]$ uname -n;id
rac1111
uid=500(oracle) gid=500(oinstall) groups=500(oinstall),501(dba),503(asmdba),505(asmadmin)
[oracle@rac1111 ~]$ ls -al
total 52
drwxr-xr-x. 4 oracle oinstall 4096 Jan 6 13:14 .
drwxr-xr-x. 6 root root 4096 Dec 29 08:17 ..
-rw------- 1 oracle oinstall 7605 Jan 14 18:29 .bash_history
-rw-r--r--. 1 oracle oinstall 18 Dec 22 2015 .bash_logout
-rw-r--r-- 1 oracle oinstall 468 Jan 5 20:23 .bash_profile