Ubuntu local shell script ssh to remote server and execute commands (expect interpreter)

Project scenario:

In work, it is often necessary to submit nodes locally and remotely log in to other nodes to execute some shell commands. If you ssh to each remote host separately, it will be very troublesome to execute each command. If you can directly ssh to each remote host to execute commands on the submission node, you can save the trouble of logging in one by one.

Realize the function:

You need to configure ssh password-free login. You can directly skip the login password and log in to the remote host directly, which is very critical when executing in shell scripts.

Operation script:

Create a new shell script with the following content.
#!/bin/expect

#设置变量
set user "holden"
set host "192.168.0.80"
set loginpass "123456"
set cmd_prompt "]#|~]?"

spawn ssh $user@$host
#设置超时时间,单位是秒
set timeout 30
# -re 匹配正则表达式
expect {
    
    
	-re "Are you sure you want to continue connecting (yes/no)?" {
    
    
		send "yes\r"
		} 
	-re "password:" {
    
    
		send "${loginpass}\r"
		} 
	-re "Permission denied, please try again." {
    
    
		exit
		}

}

###远程命令
expect {
    
     
	-re $cmd_prompt {
    
    
		send "./robosense_sdk.sh\r"
		send "exit \r"
	}

}

interact

run:

The file name is start.sh, run;
expect start.sh

Guess you like

Origin blog.csdn.net/m0_54792870/article/details/113108695