首页 > 其他 > 详细

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

时间:2014-07-06 16:22:41      阅读:415      评论:0      收藏:0      [点我收藏+]

 

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\r"
		break;
	}

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

	"FATAL" {
		puts "\nCONNECTERROR: $ip occur FATAL ERROR!!!\n"
		exit 1
	}

	timeout {
		puts "\nCONNECTERROR: $ip Logon timeout!!!\n"
		exit 1
	}

	"No route to host" {
		puts "\nCONNECTERROR: $ip No route to host!!!\n"
		exit 1
	}

	"Connection Refused" {
		puts "\nCONNECTERROR: $ip Connection Refused!!!\n"
		exit 1
	}

	"Connection refused" {
		puts "\nCONNECTERROR: $ip Connection Refused!!!\n"
		exit 1
	}

	"Host key verification failed" {
		puts "\nCONNECTERROR: $ip Host key verification failed!!!\n"
		exit 1
	}

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

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

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

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

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

expect {
	"]" {send "$commands \r"}
	"assword:" {
		send "$passwd\r"
		puts "\nPASSWORDERROR: $ip Password error!!!\n"
		exit 1
	}
}

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

expect {
	"]" {send "exit\r"}
}

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

用法:

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

 

expect实现远程主机自动执行命令脚本,布布扣,bubuko.com

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!