【问题标题】:How to execute linux commands in a remote machine with shell script如何使用 shell 脚本在远程机器上执行 linux 命令
【发布时间】:2017-11-24 03:57:21
【问题描述】:

我有一个测试服务器,我需要从它登录到两个不同的产品服务器并执行 top, free -h, ps -ef 命令 有人可以帮我写一个 shell 脚本吗

【问题讨论】:

标签: shell


【解决方案1】:

只有ssh 命令可以这样做:

$ 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

不过,这需要authenticate ssh-key相互配合。所以,我们可以用sshpass来传递passqord

$ 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

【讨论】:

    【解决方案2】:

    如果你有 ssh 访问你的服务器,你可以通过这种方式远程执行命令:

    ssh -i <PATH_YOUR_PRIVATE_KEY>remote_username@remote_host "<COMMAND>"
    

    【讨论】:

      猜你喜欢
      • 2016-04-02
      • 2011-04-26
      • 2016-03-07
      • 2012-07-27
      • 2011-12-18
      • 2015-04-24
      • 1970-01-01
      • 2012-09-14
      • 2017-09-26
      相关资源
      最近更新 更多