#!/usr/local/bin/bash
PATH=$PATH
RHOST="REMOTE_HOSTNAME"
RACCOUNT="ACCOUNT_NAME_IN_REMOTE_HOST"
RHOME="/home/${RACCOUNT}"
RSCRIPT="${RHOME}/${RACCOUNT}_scripts"
SSHKEY="/Path/to/your/SSH/private/key"
SSHCMD="ssh -2 -4 -i ${SSHKEY} ${RACCOUNT}@${RHOST}"
REMOTECMD="ls -la"
RHOSTALIVE=0
### Check REMOTE_HOST
date +"%Y/%m/%d %H:%M"
echo "Check ${RHOST}"
echo "Ping test"
RHOSTALIVE=`ping -q -c 1 -W 2 ${RHOST} > /dev/null && echo 1`
if [[ ${RHOSTALIVE} -ne 1 ]]; then
echo "Can not ping to ${RHOST}"
fi
echo "Service port test"
### Check SSH
SITE=${RHOST}
### FreeBSD : open ${SITE}
### Ubuntu : o ${SITE}
NFSSTATUS=`echo -en "open ${SITE} 22\nsend escape\nquit\nclose\n" | telnet 2>/dev/null | grep "]" | wc -l`
if [ $NFSSTATUS -ne 1 ]; then
echo "Could not connect to SSH server ${SITE}."
exit 1
else
echo "SSH server ${SITE} is alive."
fi
echo ""
### Execute remote command
echo "### Host Information ###"
REMOTECMD="hostname"
echo "Hostname : "`${SSHCMD} ${REMOTECMD}`
REMOTECMD="whoami"
echo "Account : "`${SSHCMD} ${REMOTECMD}`
REMOTECMD="pwd"
echo "Home Path : "`${SSHCMD} ${REMOTECMD}`
REMOTECMD="ls -la ${RSCRIPT}/"
echo "Scripts : "
${SSHCMD} ${REMOTECMD}
echo ""
Sunday, December 30, 2012
使用 shell script 透過 SSH 在遠端伺服器執行程式
這隻程式只是個簡單的實做連線前偵測遠端伺服器是否可以 ping 到及服務埠是否有開啟. 程式碼如下
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment