expect实现远程主机自动执行命令脚本

2014年第一个脚本,哈哈!!! expect实现远程主机自动执行命令脚本: 

#!/usr/bin/expect --

if { [llength $argv] < 4 } {
	puts "Usage: $argv0 ip user passwd port commands timeout"
	exit 1
}

match_max 600000

set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set port [lindex $argv 3]
set commands [lindex $argv 4]
set timeoutflag [lindex $argv 5]

set yesnoflag 0
set timeout $timeoutflag


for {} {1} {} {
# for is only used to retry when "Interrupted system call" occured

spawn /usr/bin/ssh -q -l$user -p$port $ip

expect 	{

	"assword:" {
		send "$passwd
"
		break;
	}

	"yes/no)?" {
		set yesnoflag 1
		send "yes
"
		break;
	}

	"FATAL" {
		puts "
CONNECTERROR: $ip occur FATAL ERROR!!!
"
		exit 1
	}

	timeout {
		puts "
CONNECTERROR: $ip Logon timeout!!!
"
		exit 1
	}

	"No route to host" {
		puts "
CONNECTERROR: $ip No route to host!!!
"
		exit 1
	}

	"Connection Refused" {
		puts "
CONNECTERROR: $ip Connection Refused!!!
"
		exit 1
	}

	"Connection refused" {
		puts "
CONNECTERROR: $ip Connection Refused!!!
"
		exit 1
	}

	"Host key verification failed" {
		puts "
CONNECTERROR: $ip Host key verification failed!!!
"
		exit 1
	}

	"Illegal host key" {
		puts "
CONNECTERROR: $ip Illegal host key!!!
"
		exit 1
	}
		
	"Connection Timed Out" {
		puts "
CONNECTERROR: $ip Logon timeout!!!
"
		exit 1
	}

	"Interrupted system call" {
		puts "
$ip Interrupted system call!!!
"
	}
}
}

if { $yesnoflag == 1 } {
	expect {
		"assword:" {
			send "$passwd
"
		}

		"yes/no)?" {
			set yesnoflag 2
			send "yes
"
		}
	}
}

if { $yesnoflag == 2 } {
	expect {
		"assword:" {
			send "$passwd
"
		}
	}
}

expect {
	"]" {send "$commands 
"}
	"assword:" {
		send "$passwd
"
		puts "
PASSWORDERROR: $ip Password error!!!
"
		exit 1
	}
}

expect {
	"]" {send "sleep 1 
"}
}

expect {
	"]" {send "exit
"}
}

expect eof {
	puts "OK_SSH: $ip
"
	exit 0;
}

用法:

./ssh.exp
Usage: ./ssh.exp ip user passwd port commands timeout

 

原文地址:https://www.cnblogs.com/L-H-R-X-hehe/p/3825320.html