文章摘要
本文介绍了一个Bash脚本,用于实现远程文件传输和执行远程命令的功能。脚本包含两个主要函数:`download`和`remoteCmd`。`download`函数通过SCP协议将本地文件传输到远程服务器,并处理文件存在性和权限等问题;`remoteCmd`函数用于执行远程命令,并处理命令执行过程中的各种响应,如确认、权限错误、输入密码和退出等。脚本最后调用`remoteCmd`函数执行了`ls -l`命令。该脚本通过错误处理机制确保远程操作的安全性和稳定性。
#!/bin/bash
remoteIp=IP
remoteUser=用户名
remotePw=密码
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”
© 版权声明
文章版权归作者所有,未经允许请勿转载。



