Linux - expect自动化远程登录脚本
简单模式:
#!/usr/bin/expect -f set timeout 5 spawn ssh root@192.168.0.1 expect "*assword*" send "root\r" expect "#" send "ifconfig \r" expect eof
讲解:
send:用于向进程发送字符串 expect:从进程接收字符串 比如:expect "*assword*" spawn:启动新的进程 interact:允许用户交互
怎么使用变量:
#!/usr/bin/expect -f set port 22 set user root set host 192.168.0.12 set password root set timeout -1 spawn ssh -D $port $user@$host "ifconfig" expect { "*yes/no" { send "yes\r"; exp_continue} "*assword:" { send "$password\r" } } expect "*#*" send "ifconfig > /home/cfg \r" send "exit\r" }
讲解:
expect { "*yes/no" { send "yes\r"; exp_continue} "*assword:" { send "$password\r" } }
选择模式,exp_continue表示继续。
通过读取配置文件获取变量:
配置文件
192.168.0.1 root 192.168.0.2 root
自动化登录脚本
#!/usr/bin/expect -f set f [open ./ip r] while { [gets $f line ]>=0 } { set ip [lindex $line 0] set pwd [lindex $line 1] spawn ssh $ip expect "*password:" { send "$pwd\r" } expect "#" send "ifconfig \r" send "exit\r" interact }
讲解:
可以多台服务器循环执行,是个非常使用的方式!
自动化远程拷贝文件:
#!/usr/bin/expect -f set port 22 set user root set host 192.168.28.30 set password root set timeout -1 spawn scp $host:/home/cfg ./ expect { "*yes/no" { send "yes\r"; exp_continue} "*assword:" { send "$password\r" } } expect eof
讲解:
原理和ssh一样
远程执行命令后写入文件,再通过scp到本机服务器:
#!/usr/bin/expect -f set port 22 set user root set host 192.168.28.30 set password root set timeout -1 spawn ssh -D $port $user@$host "ifconfig" expect { "*yes/no" { send "yes\r"; exp_continue} "*assword:" { send "$password\r" } } expect "*#*" send "ifconfig > /home/cfg \r" send "exit\r" interact spawn scp $host:/home/cfg ./ expect { "*yes/no" { send "yes\r"; exp_continue} "*assword:" { send "$password\r" } } expect eof
讲解:
自动化运维,远程交互从服务器A上ssh到服务器B上,然后执行服务器B上的命令。
技术微信群:
加微信:wonter 发送:技术Q
医疗微信群:
加微信:wonter 发送:医疗Q
更多文章关注公众号:
加微信:wonter 发送:技术Q
医疗微信群:
加微信:wonter 发送:医疗Q
更多文章关注公众号:

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】