且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

expect - linux远程执行命令

更新时间:2022-09-07 20:46:17

需要的文件:
password   #远程主机的ip 密码文件
expect        #执行远程登录,执行命令的脚本文件
login.sh       #shell 脚步调用这两个文件执行操作

1
2
3
4
5
6
#!/bin/bash
for in $(awk '{print $1}' passwd.txt)              #for循环出主机ip信息
do
p=$(awk -v I="$i" '{if(I==$1)print $2}' passwd.txt)  #取出对应ip主机的密码
expect /root/login $i $p                             #传递ip和密码信息到expect
done
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/expect -f
set hostname [lindex $argv 0]       #传主机ip参数
set passwd [lindex $argv 1]         #传主机密码参数
spawn -noecho ssh root@$hostname;   #执行ssh远程登录
expect {
    "*yes/no" { send  "yes\r"; exp_continue }        #模拟输入确认字段
    "*assword:" { send  "$passwd\r"; }               #模拟输入密码字段
}
expect "]#"                                           
send "free -m\r"
send "df -hT\r"
send "exit\r"
expect eof
1
192.168.23.252 123456     #远程主机ip 和密码信息,可以添加多个主机信息一行一条主机信息

执行过程结果:

expect - linux远程执行命令








      本文转自无形于有形  51CTO博客,原文链接:http://blog.51cto.com/jinchuang/1947054,如需转载请自行联系原作者