![함수(bash) 내에서 ssh를 사용하는 방법은 무엇입니까?](https://linux55.com/image/102263/%ED%95%A8%EC%88%98(bash)%20%EB%82%B4%EC%97%90%EC%84%9C%20ssh%EB%A5%BC%20%EC%82%AC%EC%9A%A9%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95%EC%9D%80%20%EB%AC%B4%EC%97%87%EC%9E%85%EB%8B%88%EA%B9%8C%3F.png)
아래와 같은 명령어를 이용하여 로그인하여 sshpass
서버에서 일부 명령어를 실행 하려고 합니다.
SSH_ARGS='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -q'
sshpass -p 'password' ssh ${SSH_ARGS} user@IP 'sudo sed -i "/^server 0.rhel.pool.ntp.org/ { N; s/^server 0.rhel.pool.ntp.org\n/server xxx.xx.xx.xx iburst\n&/ }" /etc/ntp.conf'
sshpass -p 'password' ssh ${SSH_ARGS} user@IP 'sudo sed -i "/^#server 0.rhel.pool.ntp.org iburst/ { N; s/^#server 0.rhel.pool.ntp.org iburst\n/server xxx.xx.xx.xx iburst\n&/ }" /etc/ntp.conf'
echo "File /etc/ntp.conf is now edited"
sshpass -p 'password' ssh ${SSH_ARGS} user@IP 'sudo cat /etc/ntp.conf | grep "server xxx.xx.xx.xx iburst"'
if [ $? = 0 ];
then
sshpass -p 'password' ssh ${SSH_ARGS} user@IP 'sudo service ntpd status;sudo service ntpd restart'
else
echo "File /etc/ntp.conf is not updated in IP"
fi
그래서매번 sshpass를 반복하는 대신sshpass -p 'password' ssh ${SSH_ARGS} user@IP
, 변수나 함수로 사용하고 싶습니다 . 어떻게 하나요?
난 최선을 다 했어::
SSH_ARGS='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -q'
sshpp=`sshpass -p 'password' ssh ${SSH_ARGS} user@IP`
$sshpp 'sudo service ntpd status'
이::
SSH_ARGS='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -q'
sshpp() {
sshpass -p 'password' ssh ${SSH_ARGS} user@IP`
}
sshpp 'sudo service ntpd status'
나는 노력했다이것또한 작동하지 않습니다.
sshpass
매번 반복 하지 않고 어떻게 이것을 달성할 수 있을까요 ?
답변1
당신이 찾고있는 것은 다음과 같습니다 alias
.
alias sp='sshpass -p "password" ssh $SSH_ARGS user@IP'
따라서 다음 명령을 실행할 수 있습니다.
sp 'sudo sed -i "/^server 0.rhel.pool.ntp.org/ { N; s/^server 0.rhel.pool.ntp.org\n/server xxx.xx.xx.xx iburst\n&/ }" /etc/ntp.conf'
이러한 반복 작업을 수행하기 위한 스크립트를 작성하면 생활이 더 단순해질 수 있지만 이는 이 질문의 범위를 벗어납니다.