当shell脚本实现远程ssh访问和scp拷贝时发现网上的一些方法用不上。这里给出一个通用文件的写法:
scp.exp:s
调用方式:
#!/bin/sh
remote_ipaddr=127.0.0.2
remote_path=/home/dir/
expect scp.exp "/home/" "root@${remote_ipaddr}:${remote_path}" "PASSWORD"
#!/usr/bin/expect
set timeout 20
if {[llength $argv] < 3} {
puts "Usage:"
puts "$argv0 remote_path local_path password"
exit 1
}
set local_path [lindex $argv 0]
set remote_path [lindex $argv 1]
set passwd [lindex $argv 2]
set passwderror 0
spawn scp -r $local_path $remote_path
expect {
"*assword:*" {
if { $passwderror == 1 } {
puts "passwd is error"
exit 2
}
set timeout 1000
set passwderror 1
send "$passwd\r"
exp_continue
}
"*es/no)?*" {
send "yes\r"
exp_continue
}
timeout {
puts "connect is timeout"
exit 3
}
}
ssh.exp:
调用方式:
#!/bin/sh
currentDir=$(cd `dirname $0`;pwd)
cd $currentDir
Fun()
{
expect ssh.exp "127.0.0.1" "PassWord"
if [ $? -ne 0 ]; then
echo "ssh failed"
return 1
fi
return 0
}
Fun
#!/usr/bin/expect
set timeout 20
if {[llength $argv] < 2} {
puts "Usage:"
puts "$argv0 remote_path password"
exit 1
}
set remote_path [lindex $argv 0]
set passwd [lindex $argv 1]
set passwderror 0
spawn ssh $remote_path
expect {
"*assword:*" {
if { $passwderror == 1 } {
puts "passwd is error"
exit 2
}
set timeout 1000
set passwderror 1
send "$passwd\r"
exp_continue
}
"*es/no)?*" {
send "yes\r"
exp_continue
}
"*]#*" {
set timeout 1000
send "cd /home && sh Test.sh\r"
}
timeout {
puts "connect is timeout"
exit 3
}
}