有时我们写expect脚本就是为了在另外一台机器上执行一个命令,下面的脚本就可以通用一些。
#! /usr/bin/expect
set user [lindex $argv 0]
set ip [lindex $argv 1]
set password [lindex $argv 2]
set filename [lindex $argv 3]
set cmd [lrange $argv 4 end]
spawn ssh $user@$ip $cmd
set done 1
set timeout 10
while {$done} {
expect {
-nocase "password: " {
send "$password\n"
set done 0
}
"yes/no" { send "yes\n" }
}
}
expect -re "\n(.*)\r"
set file [open $filename "w"]
puts $file [regsub -all "\r" $expect_out(buffer) ""]
close $file
# ./ssh.exp chris necho password /tmp/1 cat /etc/passwd
如果命令复杂一点,可以先传一个文件过去,再执行。
#! /usr/bin/expect
set user [lindex $argv 0]
set ip [lindex $argv 1]
set password [lindex $argv 2]
set file [lindex $argv 3]
set dfile /tmp/1
spawn scp $env(PWD)/$file $user@$ip:$dfile
set done 1
while {$done} {
expect {
-nocase "password: " {
send "$password\n"
set done 0
}
"yes/no" { send "yes\n" }
}
}
expect -re "\n(.*)\r"
spawn ssh $user@$ip $dfile
expect -nocase "password: " {
send "$password\n"
}
expect -re "\n(.*)\r"
# ./scp.exp chris necho password sed.sh
# cat sed.sh
#!/bin/bash
# 把一个文件的第二列替换为hostname
sed "s/\(.*\)[[:blank:]]\(.*\)[[:blank:]]\(.*\)/\1 $HOSTNAME \3/" /home/chris/file
阅读(1305) | 评论(0) | 转发(0) |