Shell script telnet login

Source: Internet
Author: User
Tags echo command sybase

 

#!/bin/bash(    echo "user"    sleep 2    echo "passwd"    sleep 3    echo "do something in remote device"    sleep 3      echo "exit") | telnet IP

The above is non-interactive usage. If you need interactive usage, you can use round CT, and then supplement it later.

#! /Bin/sh
(Echo Sybase
Sleep 2
Echo Sybase
Sleep 3
Echo "\ n"
Sleep 2
Echo "Ps"
Sleep 2

Echo logout) | Telnet alpha

Or
You can use a Batch Processing Command similar to dos.
I have reproduced an article below, hoping to help
We can use shell to implement simple control flow functions, such as loops and judgments. However, manual intervention is required for scenarios that require interaction. Sometimes we may need to implement interaction functions with interactive programs, such as telnet servers. CT is used to implement this function.

Keep CT is a free programming tool language used to automatically communicate with interactive tasks without human intervention. Don libes, author of objective CT, made the following definition for objective CT when it was written in 1990: automated CT is a software suite for automatic interaction (Automated CT [is a] software suite for automatic interactive tools ). The system administrator can create scripts to provide input to commands or programs. These commands and programs are expected to be input from the terminal, generally, these inputs must be input manually. Then, you can simulate the input required by the program based on the Program prompts to execute the interactive program. It can even implement simple BBS chatbots.

Trusted CT is evolving. As time passes, it becomes more and more powerful and has become a powerful assistant to system administrators. Secondary CT must be supported by the Tcl programming language. To run secondary CT on the system, you must first install TCL.

Working principle of secondary CT

At the simplest level, secondary CT works like a universal chat script tool. The chat script was first used in the uucp network to automate specific logon sessions when computers need to establish connections.

The chat script consists of a series of CT-send pairs: CT waits for the output to output specific characters, usually a prompt, and then sends a specific response. For example, the following chat script waits for the standard output to show login: String, then sends somebody as the user name, then waits for Password: prompt, and sends a response to sillyme.

Login: Somebody password: sillyme

This script is used to implement a logon process and use a specific user name and password for logon.

The simplest script operation mode of secondary CT is essentially the same as the chat script operation mode. Next we will analyze a script that responds to the CHSH command. Let's first review the interactive command format. Assume that we change the logon script for the user Chavez. The command interaction process is as follows:

# CHSH Chavez
Changing the login shell for Chavez
Enter the new value, or press return for the default
Login Shell [/bin/bash]:/bin/tcsh
#
You can see that the command first outputs several lines of prompts and prompts you to enter a new logon shell. You must enter the user's logon shell after the prompt or press enter without modifying the logon shell.

The following is an automated CT script that can be used to automatically execute this command:

#! /Usr/bin/CT
# Change a login shell to tcsh

Set User [lindex $ argv 0]
Spawn CHSH $ user
CT "]:"
Send "/bin/tcsh"
CT EOF
Exit
This simple script can explain the features of many CT programs. Like other scripts, the first line specifies the command program used to execute the script. Here is/usr/bin/example CT. The first line of the program is used to obtain the execution parameters of the script (it is saved in the array $ argv and is a parameter starting from 0) and save it to the variable user.

The second parameter uses the spawn command of yield CT to start the script and command session. Here the CHSH command is started. In fact, the command is run in the form of derivative sub-processes.

The subsequent trusted CT and send commands are used to implement the interaction process. The script first waits for the output to appear]: String, once the CHSH output to the feature string appears in the output (generally, the feature string is usually the feature information waiting for the input at the final prompt ). Other unmatched information will be completely ignored. When the script obtains the feature string, the secondary CT sends the/bin/tcsh and a carriage return to the CHSH command. The final script waits for the command to exit (CHSH ends). Once the EOF character indicating that the sub-process has ended is received, the secondary CT script exits.

Determine how to respond

The Administrator often needs to respond to a command in different ways based on the current situation. We can see from the examples below that condition response can be very complex, and can be implemented simply by modifying the pre-processing script. The following example shows a more complex example of reverse CT-Send:

CT-Re "\ [(. *)]:"
If {$ expect_out (1, string )! = "/Bin/tcsh "}{
Send "/bin/tcsh "}
Send ""
CT EOF
In this example, the first round CT command now uses the-Re parameter, which indicates that the specified string is a regular expression rather than a normal string. In the above example, we look for a left square brackets character (which must be escaped three times (escape), so there are three symbols, because it is a special character for regular CT and regular expression) followed by zero or multiple characters, followed by a right square brackets. Here, * indicates one or more arbitrary characters. It is stored in () because the matching result is stored in a variable to implement subsequent access to the matching result.

If a match is found, check the string contained in [] to check whether it is/bin/tcsh. If not, send/bin/tcsh to the Chsh command as the input. If yes, send only one carriage return. This simple example of sending different responses to specific situations illustrates the powerful functions of reverse CT.

In a regular expression, you can include several parts in () and access them through the expect_out array. Each part is encoded from left to right in the expression, starting from 1 (0 contains the entire matching output ). () Nesting may occur. In this case, encoding is performed from the innermost layer to the outermost layer.

Usage timeout

The prompt function with the timeout function will be described in the next round CT example. This script prompts the user to enter. If no input is made within the specified time, the script times out and returns a default response. This script receives three parameters: prompt string, default response and timeout (seconds ).

#! /Usr/bin/CT
# Prompt function with timeout and default.
Set prompt [lindex $ argv 0]
Set def [lindex $ argv 1]
Set response $ def
Set tout [lindex $ argv 2]
The first part of the script is to get the running parameters and save them to internal variables.

Send_tty "$ prompt :"
Set timeout $ tout
CT ""{
Set raw $ expect_out (buffer)
# Remove final carriage return
Set response [String trimright "$ raw" "]
}
If {"$ response" = "} {set response $ def}
Send "$ response"
# Prompt function with timeout and default.
Set prompt [lindex $ argv 0]
Set def [lindex $ argv 1]
Set response $ def
Set tout [lindex $ argv 2]

This is the rest of the script. The send_tty command is used to display the prompt string, a colon, and a space on the terminal. The set timeout command sets the timeout value of all the subsequent wait CT commands for response to $ tout (the-l parameter is used to disable any timeout settings ).

The reset CT command then waits for the carriage return character to appear in the output. If you get a carriage return before the time-out, the set command will assign the user-input content to the face-changing raw. The subsequent command removes the last carriage return symbol of the user input and then assigns the value to the variable response.

Then, if the content in response is empty, set the value of response to the default value (if the user does not enter the value after the timeout or the user only enters the carriage return ). Finally, the send command adds a carriage return to the value of the response variable to the standard output.

One interesting thing is that the script does not use the spawn command. The trusted CT script interacts with any process that calls the script.

If the Script Name is prompt, it can be used in any c-style shell.

% Set a = 'prompt "enter an answer" Silence 10'
Enter an answer: Test

% Echo answer was "$"
Answer was test
The time-out period set by prompt is 10 seconds. If the time-out or the user only enters the carriage return symbol, the echo command will output

Answer was "Silence"

A more complex example

Next we will discuss an example of a more complex round CT script, which uses more complex control structures and a lot of complex interaction processes. This example is used to send the write command to any user. The message sent is from a file or from keyboard input.

#! /Usr/bin/CT
# Write to multiple users from a prepared File
# Or a message input interactively

If {$ argc <2 }{
Send_user "Usage: $ argv0 file user1 user2 ..."
Exit
}
The send_user command is used to display the standard output of the help information to the parent process (usually the user's shell.

Set nofile 0
# Get filename via the Tcl lindex Function
Set file [lindex $ argv 0]
If {$ file = "I "}{
Set nofile 1
} Else {
# Make sure message file exists
If {! = 1 }{
Send_user "$ argv0: File $ file not found ."
Exit]

This part of the implementation process script startup parameters must be a file name that stores the message to be sent or the "I" command that indicates that the message is sent and eliminated using interactive input.

The variable file is set to the value of the first parameter of the script. It is implemented by using the Tcl function lindex. This function obtains a specific element from the list/array. [] Is used to use the return value of the lindex function as the parameter of the SET command.

If the first parameter of the script is "I" in lower case, the nofile variable is set to 1. Otherwise, you can call the Tcl function isfile to verify that the file specified by the parameter exists, if it does not exist, the system reports an error and exits.

We can see that the if command is used for logical judgment. This command is followed by the judgment condition and executed within {} after the judgment condition. If the condition is false, the program block after else is run.

Set procs {}
# Start write Processes
For {set I 1 }{$ I <$ argc}
{Incr I }{
Spawn-noecho write
[Lindex $ argv $ I]
Lappend procs $ spawn_id
}
The last part uses the spawn command to start the write process to send messages to users. Here we use the for command to implement the loop control function. The loop variable is set to 1 first, and then increments accordingly. The loop body is the last {} content. Here we use the second and subsequent parameters of the script to execute a write command on the spawn and use each parameter as the user name for sending the message. The lappend command uses the internal variable $ spawn_id of the process ID that saves each spawn to construct a process ID list in the variable procs.

If {$ nofile = 0 }{
Setmesg [open "$ file" "R"]
} Else {
Send_user "enter message,
Ending with ^ D :"}

Finally, the script opens the message file based on the value of the variable nofile or prompts the user to enter the message to be sent.

Set timeout-1
While 1 {
If {$ nofile = 0 }{
If {[gets $ mesg chars] =-1} break
Set line "$ chars"
} Else {
Expect_user {
-Re ""{}
EOF break}
Set line $ expect_out (buffer )}

Foreach spawn_id $ procs {
Send $ line}
Sleep 1}
Exit
The above code shows how the actual message text is sent through an infinite loop while. The IF statement in the while loop determines how the message is obtained. In non-interactive mode, the next row of content is read from the message file, and the while loop ends when the file content ends. (The break command is used to terminate the loop ).

In interactive mode, the expect_user command receives messages from the user. When the user inputs Ctrl + D, the input ends, and the loop ends at the same time. In both cases, the variable $ line is used to save the content of the next message. When it is a message file, the carriage return will be appended to the end of the message.

Foreach cyclically traverses all spawn processes. The idnumbers of these processes are stored in the list variable $ procs To communicate with each process separately. The send command is a foreach loop body that sends a row of messages to the current write process. At the end of the while loop is a sleep command, which is mainly used to process non-interactive modes to ensure that messages are not sent to each write process too quickly. When the while loop exits, the reverse CT script ends.

Reference resources

The comprehensive CT software version contains many examples of scripts, which can be used not only to learn and understand the comprehensive CT script, but also to be a very useful tool. You can see them in/usr/doc/packages/history CT/example. In some Linux releases, some history CT scripts are stored in the/usr/bin directory.

Don libes, grouping CT, O 'Reilly & amp; Associates, 1995.

John Ousterhout, TCL and the Tk Toolkit, Addison-Wesley, 1994.

Some useful CT scripts

Autoct: This script will generate a CT script based on the user's operations at runtime. Its function is somewhat similar to the keyboard Macro Tool in the emacs editor. An automatic script may be a good start to create a custom script.

Kibitz: This is a very useful tool. Two or more users can connect to the same shell process. It can be used for technical support or training (see ).

It can also be used for other collaborative tasks that require synchronization. For example, I want to edit a letter together with another colleague so that kibitz can share the script that runs the editor and edit and view the letter content at the same time.

Tkpasswd: This script provides a GUI tool for changing the user password, including checking whether the password is in dictionary mode. This tool is a good example for learning objective CT and TK at the same time.

Http://bbs.chinaunix.net/viewthread.php? Tid = 3139
Reprinted with the author's name and Source Text

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.