300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > SSH远程登录执行命令脚本

SSH远程登录执行命令脚本

时间:2024-02-14 10:18:01

相关推荐

SSH远程登录执行命令脚本

一、简述

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

二、脚本内容

#!/bin/bashSCRIPT_NAME=`basename $0`CURRENT_DIR=$(cd "$(dirname "$0")";pwd)execute_ssh_cmd(){local host_ip=$1local user_name=$2local user_password=$3local 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 -1spawn ssh ${user_name}@${host_ip}expect {"(yes/no)?"{send "yes\n"expect "*assword:" {send "${user_password}\n"}}"*assword:"{send "${user_password}\n"}}sleep 1send "${cmd}\n"send "exit\n"expect eofEOFcat ${log_file} | grep -iE "Permission denied|failed" >/dev/nullif [ $? -eq 0 ];thenecho "Script execute failed!"return 1fireturn 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 root@192.168.233.134Password: Last login: Mon Sep 24 00:29:35 from 192.168.233.132linux:~ # cd /;df -hFilesystemSize Used Avail Use% Mounted on/dev/sda2 48G 3.7G 42G 9% /udev 997M 96K 997M 1% /devtmpfs 997M0 997M 0% /dev/shmlinux:/ # exitlogoutConnection to 192.168.233.134 closed.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。