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

随心笔谈2年前发布 admin
194 0 0

文章摘要

这篇文章介绍了如何使用Bash脚本实现远程操作。主要内容包括: 1. `download`函数:用于远程下载文件,函数会检查权限、输入密码并继续下载。如果出现权限错误或密码错误,会提示用户并退出。 2. `remoteCmd`函数:用于执行远程命令。函数会处理用户输入的命令,例如`ls -l`,并等待用户输入`exit`后退出。 3. 代码通过`spawn`命令启动远程 shell,使用`expect`处理远程终端的响应,确保脚本能够正确处理远程操作中的常见错误(如权限问题、密码错误等)。 总结:文章重点展示了如何编写Bash脚本实现远程文件下载和命令执行,并处理了远程连接中的常见问题。

#!/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”

© 版权声明

相关文章