본문 바로가기
I T/Linux

linux , shell script SSH 접속 후 명령어 날리기

by 루솨 2022. 1. 10.

Centos linux 기준

bash shell 과 expect 를 이용 하여 SSH 를 지원 하는 [ 서버 or 네트워크 or 보안 ] 장비에 대해 접속을 하고

명령어를 날릴 때 자주 사용 하는 경우가 많습니다.

### 보안상 좋지 않습니다.

 

[root@localhost]# ./ssh_script.sh IP ID PW PORT

커맨드는 파일 안 function 부분의 빨간 부분 내용을 수정 하여 사용

expect "# " { send "\r" }

 

ex)

[root@localhost]# ./ssh_script.sh 192.168.0.10 root test123 22

 

------------------------------------------------------

[root@localhost]# cat ssh_script.sh

 

#!/bin/bash
#######################################################
### parameter
#########################################################
/usr/bin/rdate -s zero.bora.net > /dev/null 2>&1
now_date=`date +%Y-%m-%d-%H-%M`
rpmcheck=`rpm -qa expect | grep expect | wc -l`
host=$1
user=$2
passwd=$3
port=$4

#######################################################
### ssh
#########################################################
function ssh
{
echo -e " " 
echo -e " " 
echo -e -n "  sctip start ? (Y/N) : "
read answer
if [ "$answer" = "y" -o "$answer" = "Y" ]; then
echo -e " "
echo -e " ### start script ###"
echo -e " "

expect <<EOF
        log_file -noappend ./${now_date}.sshlog
        set timeout 3
        spawn ssh ${user}@${host} -p ${port}
        expect "yes/no" {
                send "yes\r"
                expect "*?assword" { send "${passwd}\r" }
            } "*?assword" { send "${passwd}\r" }
        expect "# " { send "\r" }
        expect "# " { send "\r" }
        expect "# " { send "\r" }
        expect "# " { send "\r" }
        expect "# " { send "exit \r" }
        expect eof
EOF
        echo -e " "
        echo -e " ssh connect  working! finish "
        echo -e " "

else
echo -e " Incorrect input. "
exit
fi
}
#########################################################
### rpm check
#########################################################

  if [ ${rpmcheck} == "0" ]; then
  echo -e " rpm Auto install expect "
  yum install -y expect
  ssh
  else
  ssh
  fi

chmod 000 ./*.sshlog