linuxローカルスクリプトをリモートで実行するコマンド

1459 ワード

背景:
会社のリモートN台のマシンは同じスクリプトを実行する必要があり、スクリプトがすべての実行するマシンに対して有効で安全であることを確認し、以下のコマンドを使用することができる.
ch_sudo.shは実行するスクリプト名
ssh root@サーバIPアドレス「bash」マシンが多い場合は、すべてのIPアドレスのマシンをループして実行するループスクリプトを書くことができます.
ssh test@ip  sh/root/test.sh
参照先:http://blog.csdn.net/shangzhiliang_2008/article/details/8602756
sshの-tパラメータ
-t      Force pseudo-tty allocation.  This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services.  Multiple -t options force tty allocation, even if ssh has no local tty.  

リモートサーバーの仮想tty端末を提供することができます.このパラメータを加えると、リモートサーバーの仮想端末に自分の権限パスワードを入力することができます.とても安全です.
コマンドフォーマット
ssh -t -p $port $user@$ip  'cmd'  

サンプル・スクリプト
#!/bin/bash  
  
#      
ip_array=("192.168.1.1" "192.168.1.2" "192.168.1.3")  
user="test1"  
remote_cmd="/home/test/1.sh"  
  
#    ssh            
for ip in ${ip_array[*]}  
do  
    if [ $ip = "192.168.1.1" ]; then  
        port="7777"  
    else  
        port="22"  
    fi  
    ssh -t -p $port $user@$ip "remote_cmd"  
done  

後記
この方法はやはり便利で、-tは1つのリモートサーバーの端末を仮想化して、複数のサーバーが同時に配置する時確かに多くの時間を節約しました!