How to execute linux commands in a remote machine with shell script
我有一个测试服务器,从中我需要登录到两个不同的prod服务器并执行top,free-h,ps-ef命令有人能帮我写个剧本吗
如果您有对服务器的ssh访问权,则可以通过以下方式远程执行命令:
1 | ssh -i <PATH_YOUR_PRIVATE_KEY>remote_username@remote_host"<COMMAND>" |
只有
1 2 3 4 5 6 7 8 9 10 | $ for ip in 192.168.138.22{1,2,3}; do ssh ${ip} -o StrictHostKeyChecking=no"free -h"; done total used free shared buff/cache available Mem: 7.8G 782M 5.2G 152M 1.8G 6.4G Swap: 7.9G 0B 7.9G total used free shared buff/cache available Mem: 7.8G 1.3G 4.1G 169M 2.5G 5.8G Swap: 7.9G 0B 7.9G total used free shared buff/cache available Mem: 7.8G 563M 5.9G 118M 1.4G 6.6G Swap: 7.9G 0B 7.9G |
然而,这需要彼此配合。因此,我们可以使用sshspass来传递
1 2 3 4 5 6 7 8 9 10 | $ for ip in 192.168.138.22{1,2,3}; do sshpass -p PASSWORD ssh ${ip} -o StrictHostKeyChecking=no"free -h"; done total used free shared buff/cache available Mem: 7.8G 782M 5.2G 152M 1.8G 6.4G Swap: 7.9G 0B 7.9G total used free shared buff/cache available Mem: 7.8G 1.3G 4.1G 169M 2.5G 5.8G Swap: 7.9G 0B 7.9G total used free shared buff/cache available Mem: 7.8G 563M 5.9G 118M 1.4G 6.6G Swap: 7.9G 0B 7.9G |