您的位置:首页 > 运维架构 > Shell

在远程服务器上执行本地的shell脚本

2016-06-17 19:19 519 查看
1 使用ssh实现

ssh user@hostname -C "/bin/bash" < test.sh


2 使用expect实现

采用的策略就是先在本地通过expect把shell脚本推送到远程服务器上,之后再用expect模拟登录之后,先给远程的shell脚本权限,然后再执行脚本,

最后删除脚本就ok啦!PS:在expect和控制台交互的时候我设置的timeout时间是1s,如果执行的shell脚本时间比较长的话,timeout应该大于shell脚本的时长

下面是expect脚本的代码:

#!/home/map/.jumbo/bin/expect
set serverPwd [lindex $argv 0] #服务器密码
set serverIp [lindex $argv 1] #服务器IP
set address [lindex $argv 2]  #服务器存放路径
set file [lindex $argv 3] #脚本名
set timeout 5 #手动设置与控制台交互的时间
#将shell脚本推送到远程服务器
spawn scp $file $serverIp:$address
expect {
"*yes/no*" {send "yes\r"; exp_continue}
"*password:" {send "$serverPwd\r"; exp_continue}
"*Password:" {send "$serverPwd\r"}
}
#登录远程服务器
spawn  ssh $serverIp
expect {
"*yes/no*" {send "yes\r"; exp_continue}
"*password:" {send "$serverPwd\r"; exp_continue}
"*Password:" {send "$serverPwd\r"}
}
expect "#"
#给shell脚本添加权限
send "chmod a+x $address$file\r"
expect "#"
#执行shell脚本
send "$address$file $address\r"
expect "#"
#删除远程服务器上的shell脚本
send "rm $address$file\r"
expect "#"
#退出
send "exit\r"
expect eof
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: