ssh remote connection to send command line

Reference: https://www.cnblogs.com/softidea/p/6855045.html

 

shell Remote execution:

  Often need to remotely on the other nodes perform some shell commands, if separately on each host ssh to execute a lot of trouble to go to, so to have a centralized management approach just fine. He describes two methods to remotely execute shell commands.

Prerequisites:

  Configuring ssh password-free login

For simple command:

  If you perform a few simple commands, then:

ssh user@remoteNode "cd /home ; ls"

  Basically complete common management for the remote node, and a few points to note:

  1. Double quotes, there must be. If you do not double quotes, the second ls command is performed locally
  2. A semicolon, two commands separated by semicolons

For the script way:

  Some remote command execution content is more, a single command can not be completed, to consider ways to achieve the script:

#!/bin/bash
ssh user@remoteNode > /dev/null 2>&1 << eeooff
cd /home
touch abcdefg.txt
exit
eeooff
echo done!

The contents of the remote execution "<< eeooff" to between "eeooff", the operation on the remote machine is located wherein the point to note:

  1. << eeooff, after ssh until it encounters such content eeooff end, eeooff can be easily modified into other forms.
  2. Redirect the output of the remote object that is not shown
  3. In the end, add exit to exit the remote node

http://www.cnblogs.com/ilfmonday/p/ShellRemote.html

Contents [ hide ]

SSH command format

usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]  
           [-D [bind_address:]port] [-e escape_char] [-F configfile]  
           [-I pkcs11] [-i identity_file]  
           [-L [bind_address:]port:host:hostport]  
           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]  
           [-R [bind_address:]port:host:hostport] [-S ctl_path]  
           [-W host:port] [-w local_tun[:remote_tun]]  
           [user@]hostname [command]  

The main parameters Description

Login User Specifies -l
-p is set to the port number
-f the background, and the recommended parameters plus -n
-n redirects standard input to / dev / null, prevent the reading of standard input. If ssh, then run in the background (-f option), you need this option.
-N Do not execute a remote command, the only port forwarding
-q quiet mode, ignoring all dialogue and error
-T Disable pseudo terminal configuration
-t (tty) for the ssh process on the remote system assigns a pseudo-tty (terminal). If you do not use this option, when you run a command on the remote system, ssh does not allocate tty (terminal) for the process. Instead, ssh will be the standard input and standard output attached to the distal end of the process of ssh session up, which is usually what you want (but not always). This option will force tty allocation ssh on the remote system, so that those who require a tty program will be able to operate normally.
-v verbose) Displays debugging information about the connection and transfer. If the command is not normal, this option will be very useful.

ssh host remote control, remote command execution step

The first step, set up ssh authentication-free, free certification is not password authentication can log in directly, which is especially useful when writing the script server control.

Each two-step, that is, up to a remote server execute the command

Ready to work

Based on public and private key authentication (refer to: Linux SSH key to log Detailed configuration and client test using no password) or a user name and password authentication (refer to: SSH using expect automatically enter the password, the command to achieve non-interactive password authentication) to ensure that Log on to the remote server
cmd if the script is, pay attention to the problem of absolute path (relative path is to pit when the remote execution)

Based on lack of public and private key to authenticate the remote login possible

The meet most of our needs, but usually the deployment of the operation and maintenance of a lot of things when you need root privileges, but there are a few restrictions:
The remote server prohibit root logins
to change their identity in a remote server script needs to send the password using expect, this is not safe enough

ssh remote command execution format

ssh [options] [user@]host [command]

Where, host to want to connect to the OpenSSH server (remote system) The name, which is the only required parameter. may be a host name of a local system, the FQDN may be a system on the Internet (see Glossary) or an IP address. Ssh host command to log in to a remote system host, using exactly the same user name on the user name being used by the local system. If you want to login user name and user name is being used on local systems, then it should contain user @. Depending on the server settings, you may also need to provide a password.

Open a remote shell

If no command parameter, ssh will let you log on to host up. Remote system displays a shell prompt, and then you can run commands on the host. Exit command closes connection to the host, and returns to the local system prompt.

Example: command line execution log in and execute commands on the target server

ssh user@remoteNode "cd /home ; ls"

Basically completed for the common management of the remote node, a few points to note:
If you want to execute a plurality of successive commands on a remote machine, can be single or double quotes enclose these commands. If not single or double quotes, second ls command executed locally. E.g. ssh user @ node cd / local ls ls is performed only cd / local command, ls command is executed locally, they are double or single quotes, were enclosed as a parameter ssh command is a command, it will remote continuously.
A semicolon, two commands separated by semicolons

Example: batch command execution on the target server.

#!/bin/bash  
ssh [email protected]   < < remotessh  
killall -9 java  
cd /data/apache-tomcat-7.0.53/webapps/  
exit  
remotessh  

Remote execution of content between the "<<remotessh" to "remotessh", operating on the remote machine is located which point to note: << remotessh, after ssh until it encounters such content remotessh end, you can easily modify remotessh into other forms. In the end, add exit to exit the remote node if you do not appear in the log file can modify the configuration of the machine

ssh [email protected] > /dev/null 2>&1   < < remotessh

ssh -t parameters of

-t      Force pseudo-tty allocation.  This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services.  Multiple -t options force tty allocation, even if ssh has no local tty.  

Chinese translation of this: that we can provide a virtual tty terminal to a remote server, coupled with this parameter we can provide the right to enter your password on the virtual remote terminal server, very safe
command format

ssh -t -p $port $user@$ip  'cmd'  

Sample script

#!/bin/bash  
  
#变量定义  
ip_array=("192.168.1.1" "192.168.1.2" "192.168.1.3")  
user="test1"  
remote_cmd="/home/test/1.sh"  
  
#本地通过ssh执行远程服务器的脚本  
for ip in ${ip_array[*]}  
do  
    if [ $ip = "192.168.1.1" ]; then  
        port="7777"  
    else  
        port="22"  
    fi  
    ssh -t -p $port $user@$ip "remote_cmd"  
done  

This method is very convenient, -t a virtual terminal to a remote server when deploying multiple servers at the same time really save a lot of time ah!

Example: View information about the remote server cpu
assume the remote server IP is 192.168.110.34
SSH the -l the WWW-Online 192.168.110.34 "CAT / proc / cpuinfo"

Example: Perform the remote server sh file
First create a script in uptimelog.sh remote server / home / www-online /

#!/bin/bash  
  
uptime >> 'uptime.log'  
  
exit 0

Increase the use of executable permissions chmod

chmod u+x uptimelog.sh

Remote call in the local uptimelog.sh

ssh -l www-online 192.168.110.34 "/home/www-online/uptimelog.sh"

After execution, the remote server's / home / www-online / will see uptime.log file, the contents of the display uptime

www-online@nmgwww34:~$ tail -f uptime.log  
21:07:34 up 288 days,  8:07,  1 user,  load average: 0.05, 0.19, 0.31  

Example: perform a remote sh running in the background
first of all uptimelog.sh changed a bit, modified to execute the command loop. Each second function is to write uptime.log uptime

#!/bin/bash  
  
while :  
do  
  uptime >> 'uptime.log'  
  sleep 1  
done  
  
exit 0

We need to run this sh station mode after the remote server, the command is as follows:
SSH-the -l the WWW Online 192.168.110.34 "/home/www-online/uptimelog.sh &"

www-online@onlinedev01:~$ ssh -l www-online 192.168.110.34 "/home/www-online/uptimelog.sh &"  
[email protected]'s password: 

After entering your password, found has been stopped, but can be seen on a remote server, the program has run a later stage.

www-online@nmgwww34:~$ ps aux|grep uptimelog.sh  
1007     20791  0.0  0.0  10720  1432 ?        S    21:25   0:00 /bin/bash /home/www-online/uptimelog.sh

The reason is because uptimelog.sh has been in operation, and there is no return, so the caller has been in a wait state.
Let's kill off uptimelog.sh process the remote server, then map this problem to resolve.

and can automatically exit solutions after calling ssh remote command
can be standard output and standard error output is redirected to / dev / null, so it will not have been in a wait state.
ssh -l www-online 192.168.110.34 "/home/www-online/uptimelog.sh > / dev / null 2> & 1 &"

www-online@onlinedev01:~$ ssh -l www-online 192.168.110.34 "/home/www-online/uptimelog.sh > /dev/null 2>&1 &"  
[email protected]'s password:  
www-online@onlinedev01:~$  

But the ssh process will run in the background, a waste of resources, so we need to automatically clean up these processes.

In fact, I want to quit ssh, ssh we can kill off the process to achieve after the completion of the implementation of ssh.
First, create a sh execute the command ssh, ssh here need to use the -f and -n parameters, because we also need to ssh later stage run, so that it can obtain the process number for the kill operation.
Creating ssh_uptimelog.sh, the following script

#!/bin/bash  
  
ssh -f -n -l www-online 192.168.110.34 "/home/www-online/uptimelog.sh &" # 后台运行ssh  
  
pid=$(ps aux | grep "ssh -f -n -l www-online 192.168.110.34 /home/www-online/uptimelog.sh" | awk '{print $2}' | sort -n | head -n 1) # 获取进程号  
  
echo "ssh command is running, pid:${pid}"  
  
sleep 3 && kill ${pid} && echo "ssh command is complete" # 延迟3秒后执行kill命令,关闭ssh进程,延迟时间可以根据调用的命令不同调整  
  
exit 0  

You can see, it will automatically exit after 3 seconds

www-online@onlinedev01:~$ ./ssh_uptimelog.sh  
[email protected]'s password:  
ssh command is running, pid:10141  
ssh command is complete  
www-online@onlinedev01:~$  

Then view the remote server, you can see uptimelog.sh normally performed in the background.

www-online@nmgwww34:~$ ps aux|grep uptime  
1007     28061  0.1  0.0  10720  1432 ?        S    22:05   0:00 /bin/bash /home/www-online/uptimelog.sh  

View uptime.log, has written uptime of data per second.

www-online@nmgwww34:~$ tail -f uptime.log  
22:05:44 up 288 days,  9:05,  1 user,  load average: 0.01, 0.03, 0.08  
22:05:45 up 288 days,  9:05,  1 user,  load average: 0.01, 0.03, 0.08  
22:05:46 up 288 days,  9:05,  1 user,  load average: 0.01, 0.03, 0.08  
22:05:47 up 288 days,  9:05,  1 user,  load average: 0.01, 0.03, 0.08  
22:05:48 up 288 days,  9:05,  1 user,  load average: 0.01, 0.03, 0.08  

Appendix:
1, the difference between single and double quotes in the command ssh:
an example to illustrate the problem,

Suppose arranged JAVA environment variables on the local machine, the implementation of the local echo $ JAVA_HOME = / opt / jdk

If I want to see JAVA environment variable on the remote machine, you can only use single quotation marks, ssh user @ node 'echo $ JAVA', it is '' in the $ JAVA shell will not be resolved, but as a string In this case the parameters passed to the echo $ JAVA SSH;

If we use the ssh user @ node "echo $ JAVA", the first shell will parse $ JAVA, get its value, the command becomes ssh user @ node 'echo / opt / jdk' the

2, problems may be encountered
problems: Pseudo-terminal will not be allocated because stdin is when a remote login host not a terminal error.
Solution: The literal meaning is a pseudo-terminal can not be allocated because the standard input is not a terminal.

It is necessary to increase the pseudo -t -t parameter to force the terminal is assigned, even when the standard input is not a terminal.
to force pseudo-tty allocation even if stdin is not a terminal.

Reference Sample follows:
SSH -t -t -p user1 @ host1 9527

Guess you like

Origin blog.csdn.net/Lin_QC/article/details/91570316