SHH部署脚本

两篇文章简单记录一下这周使用过的几个脚本。首先是shell脚本实现ssh自动输入密码登录主机,并在主机部署脚本并执行。
待执行脚本send_data.sh实现从配置文件server.conf读服务器地址,并向地址某端口连续发送数据。
server.conf文件信息格式:

server_address: [email protected]
server_port: 80

发送信息脚本

send_data.sh脚本首先从配置文件读取目标addr和port,根据传入的参数第一个web/ssh来选择目标端口,根据第二个参数选择发送次数:

#read config
CK_PATH=$(cd `dirname "$0"`; pwd)
BIN_PATH=$PACK_PATH

server_addr=$(cat $BIN_PATH/server.conf | grep server_address | awk '{print $2}')
server_port=$(cat $BIN_PATH/server.conf | grep server_port | awk '{print $2}')
master_host=${master_addr:4}


if [ "$1" == "web" ];then
    i=0
    while [[ $i -lt $2 ]]
    do
        echo "send test to $server_host port $server_port"
        echo "test" | nc $master_host  $server_port
        let "i+=1"
    done
elif [ "$1" == "ssh" ];then
    i=0
    while [[ $i -lt $2 ]]
    do
        echo "send test to $server_host port 22"
        echo "test" | nc $server_host  22
        let "i+=1"
    done
fi

echo "send data over to $server_host"

脚本部署:

脚本部署实现从配置文件ssh.conf中得到希望部署到的主机地址和密码,然后将脚本scp到目标主机,并在该主机执行脚本send_data.sh。
ssh.conf文件格式:

xxx@hostname1 passwd1
xxx@hostname2 passwd2

部署脚本deploy.sh:

PACK_PATH=$(cd `dirname "$0"`; pwd)

while read line; do
    host=$(echo $line | awk '{print $1}' )
    passwd=$(echo $line | awk '{print $2}')
    #scp senddata.py to remote host
    #expect ./exp/ssh.exp  $host $passwd  "rm -r ~/tmp"
    expect ./exp/scp.exp  $host $passwd $PACK_PATH
    expect ./exp/ssh.exp  $host $passwd  "sh ~/bbs1.2/senddata.sh web 2000000000"
done < ssh.conf
echo "end deploy and run"

ssh自动输入密码

由于希望实现密码自动输入,这里使用expect(可能需要安装),将scp功能和执行命令功能放在不同的两个文件:

/exp/scp.exp:

#!/usr/bin/expect

#set commend [lindex $argv 0]
set remote_path [lindex $argv 0]
set loacl_dir [lindex $argv 2]
set passwd [lindex $argv 1]

spawn scp -r $loacl_dir $remote_path:~
expect "*assword:*"
send "$passwd\r"
expect eof

/exp/ssh.exp:

#!/usr/bin/expect

set remote_path [lindex $argv 0]
set commend [lindex $argv 2]
set passwd [lindex $argv 1]

spawn ssh $remote_path $commend
expect "*assword:*"
send "$passwd\r"
expect eof

测试脚本:

运行命令

sh deploy.sh

实现向server主机的80端口发送2000000000次“test”。代码很多参数也可从命令行读取。

原创文章,原文到我的博客
更多关注公众号:

SHH部署脚本_第1张图片
wechat

你可能感兴趣的:(SHH部署脚本)