1.需求
linux shell实现使用expect命令自动交互密码远程在其它主机卸载httpd软件
2.shell脚本
expect-remove.sh
#!/bin/bash
#使用expect命令自动交互密码远程在其它主机安装httpd软件
rm -rf /root/.ssh/known_hosts
#删除/root/.ssh/known_hosts文件,ssh远程任何主机都会询问是否确认要连接该主机
expect <<EOF
spawn ssh root@192.168.10.244
#安装完此expect后,expect/spawn/send命令才能使用
expect "yes/no" {send "yes\r"}
expect "password" {send "root\r"}
#基于实际替换root密码
expect "#" {send "yum remove httpd httpd-tools\r"}
#使用yum方式进行卸载,远程主机需要提前配置好yum源
expect "y/N" {send "y\r"}
expect "#" {send "exit\r"}
EOF
验证
[root@elasticsearch ~]# sh expect-remove.sh
spawn ssh root@192.168.10.244
The authenticity of host '192.168.10.244 (192.168.10.244)' can't be established.
ECDSA key fingerprint is SHA256:EADmS0F6cqxJ00yk8pc9FgPizA/kfgBDdJTOnzrLX6Q.
ECDSA key fingerprint is MD5:33:23:05:13:40:23:ad:ae:39:9d:5a:cb:cb:b9:e1:1b.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.10.244' (ECDSA) to the list of known hosts.
root@192.168.10.244's password:
Last login: Thu May 9 15:20:18 2024 from elasticsearch
[root@logstash ~]# yum remove httpd httpd-tools
Loaded plugins: fastestmirror
Resolving Dependencies
There are unfinished transactions remaining. You might consider running yum-complete-transaction, or "yum-complete-transaction --cleanup-only" and "yum history redo last", first to finish them. If those don't work you'll have to try removing/installing packages by hand (maybe package-cleanup can help).
--> Running transaction check
---> Package httpd.x86_64 0:2.4.6-99.el7.centos.1 will be erased
---> Package httpd-tools.x86_64 0:2.4.6-99.el7.centos.1 will be erased
--> Finished Dependency Resolution
Dependencies Resolved
=============================================================================================================================================================
Package Arch Version Repository Size
=============================================================================================================================================================
Removing:
httpd x86_64 2.4.6-99.el7.centos.1 @updates 9.4 M
httpd-tools x86_64 2.4.6-99.el7.centos.1 @updates 168 k
Transaction Summary
=============================================================================================================================================================
Remove 2 Packages
Installed size: 9.5 M
Is this ok [y/N]: y
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Erasing : httpd-2.4.6-99.el7.centos.1.x86_64 1/2
Erasing : httpd-tools-2.4.6-99.el7.centos.1.x86_64 2/2
Verifying : httpd-2.4.6-99.el7.centos.1.x86_64 1/2
Verifying : httpd-tools-2.4.6-99.el7.centos.1.x86_64 2/2
Removed:
httpd.x86_64 0:2.4.6-99.el7.centos.1 httpd-tools.x86_64 0:2.4.6-99.el7.centos.1
Complete!
[root@logstash ~]# [root@elasticsearch ~]#
远程主机验证
[root@logstash .ssh]# rpm -qa | grep httpd
[root@logstash .ssh]#