写了一个expect脚本 执行ssh命令远程登录 然后telnet另外一台机器
大致如下:
1 #!/usr/bin/expect -f 2 set timeout 60 3 set port_type [lindex $argv 0] 4 set p1 [lindex $argv 1] 5 set p2 [lindex $argv 2] 6 set p3 [lindex $argv 3] 7 set p4 [lindex $argv 4] 8 set p5 [lindex $argv 5] 9 10 if { $port_type eq "http" } { 11 #puts "{"retcode":"0","retinfo":"in-http"}" 12 #puts "port_type=$port_type p1=$p1 p2=$p2 p3=$p3 p4=$p4 p5=$p5 p6=$p6" 13 spawn ssh $p2@$p1 14 expect_after eof { exit 0 } 15 16 expect "yes/no" { send "yes " } 17 expect "*assword:" { send "$p3 " } 18 19 #spawn 20 #expect "Welcome" { send "telnet $p4 $p5 " } 21 expect "*#" { send "telnet $p4 $p5 " } 22 expect "Connected to" { puts "{"retcode":"0","retinfo":"success"}" 23 exit 24 } 25 puts "{"retcode":"-2","retinfo":"fail"}" 26 27 } elseif { $port_type eq "mysql" } { 28 set p6 [lindex $argv 6] 29 set p7 [lindex $argv 7] 30 #puts "{"retcode":"0","retinfo":"in-mysql"}" 31 #puts "port_type=$port_type p1=$p1 p2=$p2 p3=$p3 p4=$p4 p5=$p5 p6=$p6 p7=$p7" 32 spawn ssh $p2@$p1 33 expect_after eof { exit 0 } 34 35 expect "yes/no" { send "yes " } 36 expect "*assword:" { send "$p3 " } 37 38 expect "Welcome" { send "mysql -h $p4 -P $p5 -u $p6 -p $p7 " } 39 expect "#" { send "mysql -h $p4 -P $p5 -u $p6 -p $p7 " } 40 expect "$" { send "mysql -h $p4 -P $p5 -u $p6 -p $p7 " } 41 42 expect "Welcome to the MySQL" { 43 puts "{"retcode":"0","retinfo":"success"}" 44 exit 45 } 46 puts "{"retcode":"-2","retinfo":"fail"}" 47 } elseif { $port_type eq "oracle" } { 48 set p6 [lindex $argv 6] 49 set p7 [lindex $argv 7] 50 set p8 [lindex $argv 8] 51 #puts "{'retcode':0,'retinfo':'into-oracle'}" 52 #puts "{"retcode":"0","retinfo":"in-mysql"}" 53 #puts "port_type=$port_type p1=$p1 p2=$p2 p3=$p3 p4=$p4 p5=$p5 p6=$p6 p7=$p7 p8=$p8" 54 spawn ssh $p2@$p1 55 expect_after eof { exit 0 } 56 57 expect "yes/no" { send "yes " } 58 expect "*assword:" { send "$p3 " } 59 60 expect "Welcome" { send "sqlplus $p4/$p5@//$p6:$p7/$p8 " } 61 expect "#" { send "sqlplus $p4/$p5@//$p6:$p7/$p8 " } 62 expect "$" { send "sqlplus $p4/$p5@//$p6:$p7/$p8 " } 63 64 expect "SQL*Plus" { 65 puts "{"retcode":"0","retinfo":"success"}" 66 exit 67 } 68 puts "{"retcode":"-2","retinfo":"fail"}" 69 } 70 #interact
然后PHP中 :
$a = system('expect.sh');
然后用xshell客户端执行
curl -d "{"interface":"test","p1":"http","p2":"120","p3":"127.0.0.52","p4":"username","p5":"password","tel_ip":"127.0.0.53","tel_port":"80"}" "http://www.test.com/test.php"
这时候xshell会显示所有expect执行步骤 所以初步尝试修改成了
exec('expect.sh',$a);
结果虽然不会直接显示在xshell客户端 但是还是会把所有执行步骤的代码输出到$a里面 而我本来只是想把expect里面的puts “sometext”命令的输出返回给$a 后来问同事 知道了可以修改成
$a = exec('expect.sh');
这样就完美解决问题了!!