zoukankan      html  css  js  c++  java
  • [shell]用shell脚本将本地文件夹与ftp上的文件夹同步

    需求说明

    最近在AIX上做开发,开发机器在office网段,测试机器在lab网段,不能互相通讯,只能通过特定的ftp来传文件。

    每次上传的机器都要做:登录ftp,进入我的目录,上传;下载的机器都要做:登录ftp,进入我的目录,下载。以上动作每天都要做几十次,很蛋疼。

    这个shell脚本的功能就是完成这些功能:登录ftp,进入我的目录,上传/下载某些文件。要传入一个参数,这个参数如果是“get”,那就从ftp下载;如果是“put”,那就上传到ftp。

    因为从来没有用过shell脚本,所以将一些关键点记录下来,以便今后揣摩。

    脚本代码

    主要流程:

    1. 判断是不是有一个参数,参数是不是“get”或者“put”,不满足的话就打印错误并退出。
    2. 将登陆ftp,进入目录的动作写入一个临时的shell脚本。
    3. 如果参数是“get”,将下载所有文件的代码写入临时脚本。如果参数是“put”,取到本地文件夹的所有文件,逐个将上传代码加入临时脚本。
    4. 将断开ftp的代码写入临时文件。
    5. 执行临时文件并删除。
     1 #!/bin/sh
     2 
     3 if [ $# -ne 1 ] ; then
     4 echo "parameter error"
     5 exit
     6 else
     7 if [ $1 != "get" ] && [ $1 != "post" ] ; then
     8 echo "parameter error"
     9 exit
    10 fi
    11 fi
    12  
    13 ftp_host="10.204.16.2"
    14 ftp_user="test"
    15 ftp_password="testtest"
    16 folder_local="/home/smld/sync"
    17 folder_remote="/home/smid/frank/sync"
    18 temp_shell="sync_temp.sh"
    19  
    20 cat > $temp_shell << EOF
    21 ftp -v -n << !
    22 open $ftp_host
    23 user $ftp_user $ftp_password
    24 lcd $folder_local
    25 cd $folder_remote
    26 bin
    27 prompt off
    28 EOF
    29  
    30 if [ $1 =  "get" ]; then
    31 echo "add mget * into $temp_shell"
    32 echo "mget *" >> $temp_shell
    33 elif [ $1 = "put" ]; then
    34 for i in `ls $folder_local`; do
    35 echo "add put $i into $temp_shell"
    36 echo "put $i" >> $temp_shell
    37 done
    38 fi
    39  
    40 cat >> $temp_shell << EOF
    41 quit
    42 !
    43 EOF
    44  
    45 chmod 777 $temp_shell
    46 echo "execute $temp_shell"
    47 ./$temp_shell
    48 rm $temp_shell

    代码详解

    第1行

    #!/bin/sh,用来指定shell的程序路径。

    3-11行

    if条件语句:

            if [条件]; then
        elif [条件]; then
            else
            fi

    判断数字是否相等:-eq(equal)-ne(not equal),其他大于小于也类似。

    判断字符串时候相等:=(等于)!=(不等于)

    条件直接的与或:&&(与)||(或) -a(and)-o(or)

    传入参数用$1 $2 ... $9表示 ,$0表示脚本名,$@表示所有参数的数组(可以超过9个),$#表示参数个数。

    13-18行

    设置一些参数,参数赋值

    20-28行

    把一段内容输入到文件:cat 内容 > 文件名,用>会清空文件原来的内容,用>>会在文件后面追加。echo也有这样的功能。

    将多行内容作为命令的输入,EOF只是一个标志,像21行换成!作用也是一样的:

            命令 << EOF
            内容段
            EOF

    ftp相关命令:

    • 选项-v:显示详细信息
    • 选项-n:关闭自动登录(open之后不会弹出提示输入用户名密码)
    • 连接某个ftp:open 主机名
    • 登录:user 用户名 密码
    • 指定本地目录:lcd 目录
    • 转成二进制传输:bin
    • 关闭主动模式(mget的时候不会逐个文件询问y/n):prompt off

    30-38行

    for循环:

            for i in 集合; do
            done

    集合可以使用命令的结果,用``把命令包起来,例如:`ls $folder_local`

  • 相关阅读:
    LeetCode "Jump Game"
    LeetCode "Pow(x,n)"
    LeetCode "Reverse Linked List II"
    LeetCode "Unique Binary Search Trees II"
    LeetCode "Combination Sum II"
    LeetCode "Divide Two Integers"
    LeetCode "First Missing Positive"
    LeetCode "Clone Graph"
    LeetCode "Decode Ways"
    LeetCode "Combinations"
  • 原文地址:https://www.cnblogs.com/hiddenfox/p/3473010.html
Copyright © 2011-2022 走看看