SSH远程登录执行命令脚本

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36485376/article/details/82828589

一、简述

运维工作中远程登录执行命令的脚本很常用,下面分享一下我常用的脚本

二、脚本内容

#!/bin/bash

SCRIPT_NAME=`basename $0`
CURRENT_DIR=$(cd "$(dirname "$0")";pwd)

execute_ssh_cmd()
{
    local host_ip=$1
    local user_name=$2
    local user_password=$3
    local cmd="$4"
    local log_file=${CURRENT_DIR}/execute_ssh_cmd.log
    
    # 如果密码中包含$符号,需要转义以下
    user_password=`echo ${user_password} | sed 's/\\$/\\\\$/g'`
    
    /usr/bin/expect <<EOF > ${log_file}
    set timeout -1
    spawn ssh ${user_name}@${host_ip}
    expect {
        "(yes/no)?"
        {
            send "yes\n"
            expect "*assword:" { send "${user_password}\n"}
        }
        "*assword:"
        {
            send "${user_password}\n"
        }
    }
    sleep 1
    send "${cmd}\n"
    send "exit\n"
    expect eof
EOF

   cat ${log_file} | grep -iE "Permission denied|failed" >/dev/null
   if [ $? -eq 0 ];then
        echo "Script execute failed!"
        return 1
   fi
   return 0
}

execute_ssh_cmd "$@"

三、使用举例

[root@localhost opt]# ./execute_ssh_cmd.sh 192.168.233.134 root "SDjefwfefw" "cd /;df -h"
[root@localhost opt]# cat execute_ssh_cmd.log 
spawn ssh [email protected]
Password: 
Last login: Mon Sep 24 00:29:35 2018 from 192.168.233.132
linux:~ # cd /;df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda2        48G  3.7G   42G   9% /
udev            997M   96K  997M   1% /dev
tmpfs           997M     0  997M   0% /dev/shm
linux:/ # exit
logout
Connection to 192.168.233.134 closed.

猜你喜欢

转载自blog.csdn.net/weixin_36485376/article/details/82828589