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

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
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值