Shell implements SSH automatic login and shellssh Automatic Login

Source: Internet
Author: User
Tags shebang

Shell implements SSH automatic login and shellssh Automatic Login

The company uses docker for development, and always entersssh user_name@ip_stringAnd then confirm the input.passwordYou may often lose errors when you get started. As a lazy person, you must find a clever way to view the ssh command. because it requires a encrypted interaction with the server, there is no option to directly attach the password to log on, let's stop.

The other day, during a technical sharing with a colleague, he only entered one line of command../test.shI was amazed when I successfully logged on to the development machine. So I came back and searched for the article.

Shell script Basics

Before writing an ssh automatic login script, let's talk about the basis of the shell script. This is not a syntax or something. It is everywhere on the Internet. Here we summarize the running mechanism of the shell script ~

How shell scripts run

First of all, let's talk about several shell startup methods. It took two hours to use the script that was originally completed in ten minutes after script startup. At the same time, let's run shell, so we can understand it.

Run by file name

Shell scripts can be executed directly through the file name. Note that the file requires the execution permission. Passsudo chmod +x ./file_name.shTo add execution permissions to files;

Specify the script interpreter to execute the file

Our commonsh file_name.shThe script interpreter is specified./bin/shTo explain the execution script. Common script interpreters include:/bin/bashAnd so -l /bin/*shCommand to view the currently available script interpreter;

Run the script using the ../file_name or source command.

This method does not fork a sub-process to execute the script like the previous two methods, but uses the current shell environment for execution. bashrc or. when bash_profile is modified, the current change takes effect without restarting the shell or logging on to the system again.


When we write a shell script, we always get used to adding a line at the beginning#!/binbashIt is the scriptshebangAs for why such a strange name is called, the C language and Unix developer Dennis Ritchie called itIt may be a descriptive English text similar to "hash-bang ".;

Post an explanation on the wiki:

In computer science, Shebang is a string line consisting of a well number and an exclamation point. It appears in the first two characters of a text file. When Shebang exists in the file, the program loader of the Unix-like operating system will analyze the Shebang content, use the content as the interpreter instruction, and call the instruction, the file path containing Shebang is used as the parameter of the interpreter.

Simply put, it indicates the interpreter used to run the script. Therefore, shebang must be included when the shell script is directly executed using the file name, we can also add options directly after shebang. We use options by default for execution;

For exampletest.shOfshebangIs#!/bin/sh -xWhen we execute the script:

./ hello


bin/sh -x ./ hello;

The shebang (Interpreter) used to compile an ssh automatic login script is/usr/bin/expect;

Note that when the script interpreter is specified to execute the script, shebang will be overwritten by the specified script interpreter, that is, the specified script interpreter is used to execute the script first. /test. sh prompts command not found)

Secondary CT Interpreter

Keep CT is an interpreter that can implement automatic and interactive tasks. It can also explain common shell syntax commands, which are characteristic of the following commands:

Spawn command:

spawn commandThe command will fork a sub-process to execute the command, and then execute the following command in this sub-process;

In the ssh automatic login script, we usespawn ssh user_name@ip_str, Fork a sub-process to execute the ssh Login command;

CT command:

The secondary CT command is a key command of the secondary CT interpreter. Its common usage isexpect "string"That is, you want to obtain the string. You can use wildcard characters such as * in the string;

After the string matches the information returned by the command line, the reverse CT will immediately execute the script;

Set timeout command:

set timeout nThe command sets the wait time-out period of the keep CT command to n seconds. The command has not been obtained in n seconds. If keep CT is false, the script continues to run down;

Send command:

The general usage of the send command issend "string"They will input a piece of information to the command line like we normally enter the command, of course, do not forgetstringAdd later\rEnter a carriage return;

Interact command:

The interact command is very simple. When executing this command, the subprocess of the fork script gives the operation permission to the user, allowing the user to interact with the current shell;

Complete script

The following is a complete version of the

#! /Usr/bin/Reset CT // specify shebangset timeout 3 // set the timeout time to 3 seconds for spawn ssh user_name @ 172. ***. ***. * ** // fork a sub-process executes the ssh command login CT "* password *" // It is expected to match 'user _ name @ ip_string's password: 'Send "my_password \ r" // enter the password to the command line and press enter to send "sudo-s \ r" send "cd/data/logs \ r" // switch to the common working directory interact // allows users to interact with command lines

Runsudo chmod +x ./test.shCommand to add the execution permission to the shell script;

Run./test.shCommand, one-click Login successful!

After a few simple commands are combined to solve the problem of interaction with the command line, many complicated functions are useless ~


The script is complete, but there are still some flaws:

  • Input./file_name.shThe command is too long...
  • The command can only be executed in the script directory. Otherwise, the command output using the absolute path is longer.

Here we think of the linux alias command:

Alias command:

The alias command is usedalias alias_name="ori_command", Set alias_name to the alias of ori_command. In this way, we input and execute alias_name, which is equivalent to executing ori_command;

However, we will find that when you close the current shell, open a shell window and then use alias_name, the system promptscommand not found;

Is there a way to keep the command? Edit the bash_profile file.

Bash_profile File

Edit the bash_profile file. This file will be executed first when it is created in the terminal window, so you can set another alias for it;

Execute Commandvim ~./bash_profile, Add:

alias alias_name="/root_dir/../

Save and then use. ~./bash_profileOrsource ~./bash_profileExecute the alias setting command in the current script to complete the setting;

In this way, no matter which directory we are in, just enteralias_nameCommand, press enter, real one-click Login!


As a programmerLazyConsciousness (of course, this is not the case of laziness ...), In unix-like systems, do not waste it.shellThis magical tool allows computers to serve us ~

I haven't written a blog for more than a month. Recently I 've been reading a set of books on APUE and UNP. C and Unix, but I am not afraid to write the wrong books. I usually use NotePad to make my own notes, out of system;

Let's get through it. You can write appropriate projects. Thank you for your attention ~

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: 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.