shell脚本自动输入用户名和密码的实现(shell自动重启脚本)学会了吗

随心笔谈9个月前更新 admin
205 00
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买

文章摘要

本文介绍了一个Bash脚本,用于实现远程文件传输和执行远程命令的功能。脚本包含两个主要函数:`download`和`remoteCmd`。`download`函数通过SCP协议将本地文件传输到远程服务器,并处理文件存在性和权限等问题;`remoteCmd`函数用于执行远程命令,并处理命令执行过程中的各种响应,如确认、权限错误、输入密码和退出等。脚本最后调用`remoteCmd`函数执行了`ls -l`命令。该脚本通过错误处理机制确保远程操作的安全性和稳定性。

#!/bin/bash
remoteIp=IP
remoteUser=用户名
remotePw=密码

function download(){
? remoteFile=$1
? localDir=$2
? expect << EOF
? ? set timeout 1200;
? ? spawn scp -r -p $remoteUser@$remoteIp:”$remoteFile” “$localDir”
? ? expect{
? ? ? “*yes/no*” {send “yes\n”;exp_continue}
? ? ? “*Permission denied*” {exit 1}
? ? ? “*password*” {send “$remotePw\n”;exp_continue}
? ? ? “*Killed by signal 1” {exit 1}
? ? }
EOF
}

fucntion remoteCmd(){
? cmd=$1
? expect << EOF
? ? set timeout 1200;
? ? spawn ssh $remoteUser@$remoteIp
? ? expect{
? ? ? “*yes/no*” {send “yes\n”;exp_continue}
? ? ? “*Permission denied*” {exit 1}
? ? ? “*password*” {send “$remotePw\n”;exp_continue}
? ? ? “*\$ ” {send “\n”}
? ? }
? ? expect “*\$ ” {send “$cmd\n”}
? ? expect “*\$ ” {send “exit\n”}
EOF
}

remoteCmd “ls -l”

© 版权声明

相关文章