0
点赞
收藏
分享

微信扫一扫

如何写一个sh脚本将一个本地文件通过 scp命令上传到远程的 centos服务器?

微言记 2023-09-07 阅读 67

如何写一个sh脚本将一个本地文件通过 scp命令上传到远程的 centos服务器?

1.1 背景需求

这篇博文分享如何使用scpexpect命令写一个脚本来自动填充密码并实现自动登录并上传文件到服务器。

1.2 解决方案

执行脚本输入如下命令:

sh publish.sh 

执行命令脚本内容如下:

#!/bin/bash

# local host file folde path
local_dir="/Users/zhaoqingfeng/downloads/test/dist/"

# config remote server info
# remote server ip
remote_server="192.168.159.175"
# config your remote server acccount
remote_user="root"
# config your remote server password
remote_password="toor"
# config remote server target path
remote_dir="/var/www/html/your_project/"

# upload local file to remote server
expect -c "
spawn scp -r $local_dir $remote_user@$remote_server:$remote_dir
expect {
    \"*assword:\" {
        send \"$remote_password\r\"
        exp_continue
    }
    \"yes/no\" {
        send \"yes\r\"
        exp_continue
    }
    eof
}
"

# Check scp command
if [ $? -eq 0 ]; then
    echo "Upload file success!"
else
    echo "File upload fail"
fi

总体来说就是

最后执行成功如下所示:
在这里插入图片描述

1.3 附录

1.3.1 scp命令用法与示例

1.3.1.1 scp命令用法与解释

scp 命令是用于在本地计算机和远程计算机之间进行安全文件传输的工具。

它可以用来上传或下载文件和目录。以下是 scp 命令的基本用法和解释:

scp [options] source_file/directory target_file/directory

1.3.1.2 scp 命令用法示例

以下是一些示例 scp 命令用法:

1.3.1.2.1 示例一:从本地复制文件到远程计算机
scp localfile.txt user@remotehost:/remote/directory/
1.3.1.2.2 示例二:从远程计算机复制文件到本地
scp user@remotehost:/remote/file.txt /local/directory/
1.3.1.2.3 示例三:递归复制整个目录到远程计算机
scp -r local_directory/ user@remotehost:/remote/directory/
1.3.1.2.4 示例四:从远程计算机下载整个目录到本地
scp -r user@remotehost:/remote/directory/ /local/directory/

1.3.2 expect 命令用法与示例

下面是 expect 命令的一些基本用法和示例:

1.3.2.1 expect 基本用法

expect 命令的基本语法如下:

expect [选项] <期望模式> <动作>

选项:可以包括一些常见的选项,如 -c 用于指定要执行的 expect 脚本代码。

<期望模式>:这是一个正则表达式,用于匹配命令行程序的输出,以确定下一步的操作。

<动作>:这是要执行的命令或操作,通常是响应匹配到的输出。

1.3.2.2 expect 用法示例

以下是一些 expect 命令的示例:

示例 1:自动登录 SSH
#!/usr/bin/expect
set timeout 10
spawn ssh user@hostname
expect "password:"
send "your_password\r"
expect "$"
send "ls -l\r"
expect "$"
send "exit\r"
示例 2:自动化 FTP 文件传输
#!/usr/bin/expect
set timeout 10
spawn ftp ftp.example.com
expect "Name (ftp.example.com:user):"
send "your_username\r"
expect "Password:"
send "your_password\r"
expect "ftp>"
send "put localfile.txt remotefile.txt\r"
expect "ftp>"
send "quit\r"

示例 3:交互式配置脚本
#!/usr/bin/expect
set timeout 10
spawn ./configure.sh
expect "Enter your name:"
send "Your Name\r"
expect "Enter your email:"
send "your@email.com\r"
expect "Choose an option (1/2/3):"
send "2\r"
expect eof

举报

相关推荐

0 条评论