我试图通过使用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'
请注意,通过编写脚本来执行这些重复性任务可能会让您的生活更加简化,但这超出了本问题的范围。