您的位置:首页 > 运维架构 > Linux

Linux 小工具---多台机器执行命令或复制文件

2016-12-12 17:31 351 查看
今天写了一个小工具,用shell实现从一台机器往其他多台机器复制文件或者在其他多台机器执行相同命令用的。

目录结构如下,

[root@cent-1 ~]# cd tools/
[root@cent-1 tools]# ls
copy_files.sh  main.sh  run_commands.sh  servers


其中,servers里面维护要执行的节点列表,hostname或ip均可; copy_files.sh是复制文件的脚本,run_commands是执行命令的脚本,main.sh是主入口,用法如下,

[root@cent-1 tools]# ./main.sh
usage: main.sh [-e command-name] | [-c file-name]
example: $(basename $0) -e ssh-keygen
example: $(basename $0) -c /etc/hosts


“-e”表示执行一个命令,后面接命令;”-c”表示复制一个文件,后面接文件全路径。

举例如下,

1 复制文件

[root@cent-1 tools]# ./main.sh -c /etc/hosts
Copy files to cent-2...


2 执行命令

[root@cent-1 tools]# cat servers
cent-1
cent-2
[root@cent-1 tools]# ./main.sh -e ssh-keygen
Run commands on cent-1...
Enter file in which to save the key (/root/.ssh/id_rsa):
Generating public/private rsa key pair.
/root/.ssh/id_rsa already exists.
Overwrite (y/n)?
Run commands on cent-2...
Enter file in which to save the key (/root/.ssh/id_rsa):
Generating public/private rsa key pair.
/root/.ssh/id_rsa already exists.
Overwrite (y/n)?


具体代码实现如下,

[root@cent-1 tools]# cat main.sh
#!/bin/bash

if [ "$#" != "2" ]; then
echo "usage: $(basename $0) [-e command-name] | [-c file-name]"
echo '  example: $(basename $0) -e ssh-keygen'
echo '  example: $(basename $0) -c /etc/hosts'
exit 1
fi

if [ "$1" == "-e" ]; then
sh run_commands.sh $2
fi

if [ "$1" == "-c" ]; then
sh copy_files.sh $2
fi

[root@cent-1 tools]# cat copy_files.sh
#!/bin/bash

if [ "$#" != "1" ]; then
echo "usage: $(basename $0) <file-name>"
echo "  example: $(basename $0) /etc/hosts"
exit 1
fi

SRC_PATH=$PWD/servers
SOURCE_FILE=$1
SOURCE_FILE_BAK=$1.bak

for srv in $(cat $SRC_PATH);do
echo "Copy files to $srv..."
ssh $srv "mv $SOURCE_FILE $SOURCE_FILE_BAK"
rsync $SOURCE_FILE $srv:$SOURCE_FILE
done

[root@cent-1 tools]# cat run_commands.sh
#!/bin/bash

if [ "$#" != "1" ]; then
echo "usage: $(basename $0) <command-name>"
echo "  example: $(basename $0) ssh-keygen"
exit 1
fi

SRC_PATH=$PWD/servers
COMMAND=$1

for srv in $(cat $SRC_PATH);do
echo "Run commands on $srv..."
ssh $srv "$COMMAND"
done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: