shell脚本远程ssh服务器并执行操作

需求:自动登录服务器并执行操作指令
使用到的命令:expect

expect是一个免费的编程工具,用来实现自动的交互式任务,而无需人为干预。

send 命令接收一个字符串参数,并将该参数发送到进程。
expect 命令和send命令相反,expect通常用来等待一个进程的反馈,我们根据进程的反馈,再发送对应的交互命令。
spawn 命令用来启动新的进程,spawn后的send和expect命令都是和使用spawn打开的进程进行交互。
interact 命令用的其实不是很多,一般情况下使用spawn、send和expect命令就可以很好的完成我们的任务;但在一些特殊场合下还是需要使用interact命令的,interact命令主要用于退出自动化,进入人工交互。比如我们使用spawn、send和expect命令完成了ftp登陆主机,执行下载文件任务,但是我们希望在文件下载结束以后,仍然可以停留在ftp命令行状态,以便手动的执行后续命令,此时使用interact命令就可以很好的完成这个任务。

代码示例:自动登录主机并执行操作

login.sh:执行时使用 expect login.sh

#!/bin/expect

#设置变量
set user "root"
set host "192.168.149.100"
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 "df -h\r"
		send "cat /etc/hosts\r"
		send "ip addr \r"
		send "echo '111111' >> /data/a.log \r"
		send "exit \r"
	}

}

interact

批量进行登录操作

ssh.exp

#!/bin/expect

set host [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set timeout 5

spawn ssh $user@$host
expect {
     
        "(yes/no)?" {
      send "yes \r" ;exp_continue }
        "*password*" {
      send "$passwd\r" ;exp_continue}
        "#" {
      send "echo '11111' >> /data/a.log \r"}
}
#expect eof

#interact

host.list

192.168.149.100 root 123456
192.168.149.101 root 123456
192.168.149.102 root 123456
192.168.149.103 root 123456

login.sh

#/bin/bash

host='host.list'
while read line
do
echo $line
expect a.exp $line
done < $host

你可能感兴趣的:(linux学习笔记)