program tip

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

radiobox 2020. 10. 18. 09:13
반응형

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. Make sure there is no screen running in the backgroud by using the command 'screen -ls'.
  2. Read http://www.gnu.org/software/screen/manual/screen.html#Stuff to read more about screen and its options.
  3. '-p' option in sample_script.sh preselects and reattaches to a specific window to send a command via the ‘-X’ option otherwise you get a 'No screen session found' error.

You can use expect scripts instaed of bash. Below example show how to telnex into an embedded board having no password

#!/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

Following is working for me... put all of your IPs you want to telnet in IP_sheet.txt

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

Use ssh for that purpose. Generate keys without using a password and place it to .authorized_keys at the remote machine. Create the script to be run remotely, copy it to the other machine and then just run it remotely using ssh.

I used this approach many times with a big success. Also note that it is much more secure than telnet.


#!/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"

Here is how to use telnet in bash shell/expect

#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed

set ip [lindex $argv 0]
set port [lindex $argv 1]

set timeout 5
spawn telnet $ip $port
expect "'^]'."

Play with tcpdump or wireshark and see what commands are sent to the server itself

Try this

printf (printf "$username\r\n$password\r\nwhoami\r\nexit\r\n") | ncat $target 23

Some servers require a delay with the password as it does not hold lines on the stack

printf (printf "$username\r\n";sleep 1;printf "$password\r\nwhoami\r\nexit\r\n") | ncat $target 23**

참고URL : https://stackoverflow.com/questions/7013137/automating-telnet-session-using-bash-scripts

반응형