linux 远程执行本地脚本的命令

背景:
公司远程N台机器需要执行同一脚本,确认脚本对所有需要执行的机器都有效安全,可以使用如下命令。

ch_sudo.sh为需要执行的脚本名称
ssh root@服务器IP地址 "bash" < ch_sudo.sh

如果机器很多,可以写一个循环脚本,对所有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虚拟出一个远程服务器的终端,在多台服务器同时部署时确实节约了不少时间啊!

猜你喜欢

转载自yingbin920.iteye.com/blog/1973182