一、简述 运维工作中远程登录执行命令的脚本很常用,下面分享一下我常用的脚本 二、脚本内容 #!/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 < 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 "$@" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 三、使用举例 [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 root@192.168.233.134 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. --------------------- |
|手机版|小黑屋|梦想之都-俊月星空
( 粤ICP备18056059号 )|网站地图
GMT+8, 2025-12-16 21:00 , Processed in 0.039416 second(s), 17 queries .
Powered by Mxzdjyxk! X3.5
© 2001-2025 Discuz! Team.