[linux] bash 스크립트를 사용하여 텔넷 세션 자동화

Bash 스크립트를 사용하여 일부 텔넷 관련 작업을 자동화하는 중입니다. 자동화되면 사용자와 텔넷의 상호 작용이 없습니다. (즉, 완전히 자동화됩니다)

스크립트는 다음과 같습니다.

# execute some commands on the local system
# access a remote system with an IP address: 10.1.1.1 (for example)

telnet 10.1.1.1

# execute some commands on the remote system
# log all the activity (in a file) on the Local system
# exit telnet
# continue on with executing the rest of the script.

여기에 두 가지 문제가 있습니다.

  1. 스크립트에서 원격 시스템에서 명령을 실행하는 방법 (인간 상호 작용없이)?

    일부 테스트 코드에 대한 경험을 통해 텔넷 10.1.1.1 이 실행될 때 텔넷이 대화 형 세션으로 들어가고 스크립트의 후속 코드 줄이 로컬 시스템에서 실행 된다는 것을 추론 할 수있었습니다 . 로컬 시스템이 아닌 원격 시스템에서 코드 줄을 어떻게 실행할 수 있습니까?

  2. 로컬 시스템의 텔넷 세션에서 활동에 대한 로그 파일을 가져올 수 없습니다. 내가 사용한 stdout 리디렉션은 원격 시스템에 복사본을 만듭니다 (로그를 로컬 시스템에 복사하기 위해 복사 작업을 수행하고 싶지 않음). 이 기능을 어떻게 얻을 수 있습니까?



답변

expect스크립트를 작성하십시오 .

다음은 그 예입니다.

#!/usr/bin/expect

#If it all goes pear shaped the script will timeout after 20 seconds.
set timeout 20
#First argument is assigned to the variable name
set name [lindex $argv 0]
#Second argument is assigned to the variable user
set user [lindex $argv 1]
#Third argument is assigned to the variable password
set password [lindex $argv 2]
#This spawns the telnet program and connects it to the variable name
spawn telnet $name
#The script expects login
expect "login:"
#The script sends the user variable
send "$user "
#The script expects Password
expect "Password:"
#The script sends the password variable
send "$password "
#This hands control of the keyboard over to you (Nice expect feature!)
interact

실행하려면 :

./myscript.expect name user password


답변

예상을 사용하는 것이 좋지만 비 대화 형 사용의 경우 일반 셸 명령으로 충분할 수 있습니다. Telnet은 stdin에서 해당 명령을 허용하므로 명령을 파이프하거나 작성하면됩니다.

telnet 10.1.1.1 <<EOF
remotecommand 1
remotecommand 2
EOF

(편집 : 주석으로 판단하면 원격 명령이 입력을 처리하는 데 약간의 시간이 필요하거나 초기 SIGHUP가 텔넷에서 정상적으로 처리되지 않습니다. 이러한 경우 입력에 대해 잠깐 절전 모드를 시도 할 수 있습니다.)

{ echo "remotecommand 1"; echo "remotecommand 2"; sleep 1; } | telnet 10.1.1.1

어쨌든 대화 형이나 다른 것이 있으면 expect.


답변

텔넷은 HTTP 프로토콜을 배울 때 자주 사용됩니다. 이 스크립트를 웹 스크래퍼의 일부로 사용했습니다.

echo "open www.example.com 80"
sleep 2
echo "GET /index.html HTTP/1.1"
echo "Host: www.example.com"
echo
echo
sleep 2

스크립트 이름이 get-page.sh라고 가정 해 보겠습니다.

get-page.sh | telnet

당신에게 html 문서를 줄 것입니다.

누군가에게 도움이되기를 바랍니다.)


답변

이거 저 한테 ..

사용자 이름과 암호가 필요한 여러 텔넷 로그인을 자동화하려고했습니다. 다른 서버의 로그를 내 컴퓨터에 저장하기 때문에 텔넷 세션은 백그라운드에서 무기한 실행되어야합니다.

telnet.sh는 ‘expect’명령을 사용하여 텔넷 로그인을 자동화합니다. 더 많은 정보는 여기에서 찾을 수 있습니다 : http://osix.net/modules/article/?id=30

telnet.sh

#!/usr/bin/expect
set timeout 20
set hostName [lindex $argv 0]
set userName [lindex $argv 1]
set password [lindex $argv 2]

spawn telnet $hostName

expect "User Access Verification"
expect "Username:"
send "$userName\r"
expect "Password:"
send "$password\r";
interact

sample_script.sh는 telnet.sh를 실행하여 각 텔넷 세션에 대한 백그라운드 프로세스를 만드는 데 사용됩니다. 자세한 내용은 코드의 주석 섹션에서 찾을 수 있습니다.

sample_script.sh

#!/bin/bash
#start screen in detached mode with session-name 'default_session' 
screen -dmS default_session -t screen_name
#save the generated logs in a log file 'abc.log' 
screen -S default_session -p screen_name -X stuff "script -f /tmp/abc.log $(printf \\r)"
#start the telnet session and generate logs
screen -S default_session -p screen_name -X stuff "expect telnet.sh hostname username password $(printf \\r)"
  1. ‘screen -ls’명령을 사용하여 배경에서 실행중인 화면이 없는지 확인하십시오.
  2. 읽기
    http://www.gnu.org/software/screen/manual/screen.html#Stuff를 화면과 그 옵션에 대한 자세한 내용을보실 수 있습니다.
  3. sample_script.sh의 ‘-p’옵션은 ‘-X’옵션을 통해 명령을 보내기 위해 특정 창을 미리 선택하고 다시 연결합니다. 그렇지 않으면 ‘No screen session found’오류가 발생합니다.


답변

bash가 삽입 된 expect 스크립트를 사용할 수 있습니다. 아래 예는 비밀번호가없는 임베디드 보드에 telnex를 연결하는 방법을 보여줍니다.

#!/usr/bin/expect

set ip "<ip>"

spawn "/bin/bash"
send "telnet $ip\r"
expect "'^]'."
send "\r"
expect "#"
sleep 2

send "ls\r"
expect "#"

sleep 2
send -- "^]\r"
expect "telnet>"
send  "quit\r"
expect eof


답변

다음은 나를 위해 일하고 있습니다 … IP_sheet.txt에 텔넷하려는 모든 IP를 넣으십시오.

while true
read a
do
{
    sleep 3
    echo df -kh
    sleep 3
    echo exit
} | telnet $a
done<IP_sheet.txt


답변

#!/bin/bash
ping_count="4"
avg_max_limit="1500"
router="sagemcom-fast-2804-v2"
adress="192.168.1.1"
user="admin"
pass="admin"

VAR=$(
expect -c "
        set timeout 3
        spawn telnet "$adress"
        expect \"Login:\"
        send \"$user\n\"
        expect \"Password:\"
        send \"$pass\n\"
        expect \"commands.\"
        send \"ping ya.ru -c $ping_count\n\"
        set timeout 9
        expect \"transmitted\"
        send \"exit\"
        ")

count_ping=$(echo "$VAR" | grep packets | cut -c 1)
avg_ms=$(echo "$VAR" | grep round-trip | cut -d '/' -f 4 | cut -d '.' -f 1)

echo "1_____ping___$count_ping|||____$avg_ms"
echo "$VAR"