zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    web端ip定位
    【树状数组2】洛谷P3368
    【树状数组1】 洛谷P3374
    【割点】洛谷P3388
    【二分图匹配】洛谷P3386
    洛谷P4145 上帝造题的七分钟2 / 花神游历各国
    【线段树2】洛谷P3373
    【线段树1】洛谷P3372
    【乘法逆元】洛谷P3811
    【LCA】洛谷P3379
  • 原文地址:https://www.cnblogs.com/L-H-R-X-hehe/p/3825320.html
Copyright © 2011-2022 走看看