鏡像:registry.cn-shanghai.aliyuncs.com/sdev/ssh-password
該鏡像用于CI docker部署時(shí)在服務(wù)器上執(zhí)行命令。
docker部署一般步驟:
node build --- build docker image --- push docker image --- run shell script on remote server
該鏡像用于最后一階段。用于推送鏡像后在服務(wù)器上拉取鏡像后運(yùn)行鏡像。
鏡像一般使用方法:
運(yùn)行時(shí)指定用戶名、密碼、主機(jī)名
docker run --rm -it \
-e SSH_USER=root \
-e SSH_HOST=47.102.122.82 \
-e SSH_PASSWORD=xxxxxxxxxxxx \
registry.cn-shanghai.aliyuncs.com/sdev/ssh-password
在容器內(nèi)指定用戶名密碼等:
export SSH_USER=root SSH_HOST=192.168.0.0.1 SSH_PASSWORD=your_password && ./run.sh "echo I am in remote."
在容器內(nèi)執(zhí)行遠(yuǎn)程命令:
./run.sh "echo I am in remote."
使用鏡像直接執(zhí)行命令
docker run --rm -e SSH_USER=root -e SSH_HOST=47.102.122.82 -e SSH_PASSWORD=xxxxxxxx. registry.cn-shanghai.aliyuncs.com/sdev/ssh-password /bin/sh ./run.sh 'ls -la'
原理
- 利用expect來輸入密碼:
首先linux安裝expect,例如apline下執(zhí)行apk add expect - shell腳本
#!/bin/sh
expect <<EOF
set timeout 5:
spawn ssh ${SSH_USER}@${SSH_HOST} sh -c \"${REMOTE_SCRIPT}\"
expect {
"*yes*" {send "yes\n"}
}
expect {
"*password*" {send "${SSH_PASSWORD}\n"}
}
expect eof
EOF
echo run commands successfully.
- 封裝docker鏡像。
將以上內(nèi)容封裝成docker鏡像即可。
執(zhí)行環(huán)境變量后執(zhí)行shell腳本即可登錄遠(yuǎn)程服務(wù)器并執(zhí)行一段腳本。