简体   繁体   English

使用nc传输文件时文件为空

[英]Empty file when transferring files using nc

I am struggling long time on the weird situation on file transferring using nc, I use the following bash script to transfer files from A machine to B machine, the script seems okay and the file is being transfer to the B machine, however the file's size is 0 byte and does not have any contents (which it really contains in machine A), then I run my script second time and this time machine B does contain content, may I know which part my script cause this problem? 我在使用nc进行文件传输时遇到了很奇怪的情况,我一直在苦苦挣扎,我使用以下bash脚本将文件从A机传输到B机,该脚本似乎还可以,并且文件正在传输到B机,但是文件大小是0字节并且没有任何内容(它实际上包含在机器A中),那么我第二次运行脚本,而这次机器B包含内容,我是否知道我的脚本的哪一部分导致了此问题? Million thanks for the help! 百万感谢您的帮助!

#!/bin/bash
IPADDRSTR="$1"
COUNT=0
for x in $IPADDRSTR
do
#server
    IPERRSTR[$COUNT]=$(sshpass -p pass ssh -o StrictHostKeyChecking=no -p 22 root@$x '$(/usr/bin/nc -l -p1234 > /root/a.txt)&' > /dev/null 2>&1 | echo -n $?)

        if [ ${IPERRSTR[COUNT]} -eq "0" ]
        then
            nc $x 1234 < ./a.txt
            echo "done"
        fi
    COUNT=$((COUNT+1))
done

rsync may be a more elegant utility here. rsync可能是一个更优雅的实用程序。 I am just going to get you started. 我只是要让您开始。 Your code seems okay to me, but they make good points above. 您的代码对我来说似乎还可以,但是上面的内容很不错。 Read about rsync here: https://www.digitalocean.com/community/tutorials/how-to-use-rsync-to-sync-local-and-remote-directories-on-a-vps 在此处阅读有关rsync的信息: https : //www.digitalocean.com/community/tutorials/how-to-use-rsync-to-sync-local-and-remote-directories-on-a-vps

#!/bin/bash
IPADDRSTR="$1"
COUNT=0
for x in $IPADDRSTR
do
#server
    IPERRSTR[$COUNT]=$(sshpass -p pass ssh -o StrictHostKeyChecking=no -p 22 root@$x '$(/usr/bin/nc -l -p1234 > /root/a.txt)&' > /dev/null 2>&1 | echo -n $?)

        if [ ${IPERRSTR[COUNT]} -eq "0" ]
        then
            #######Place rysnc command here instead.######## 
            echo "done"
        fi
    COUNT=$((COUNT+1))
done

Thanks all guys, I think I have solved the problem, here is the cause and solution 谢谢大家,我想我已经解决了问题,这是原因和解决方案

The reason why the transferred file is 0 byte is that the transfer has not even started! 传输文件为0字节的原因是传输甚至还没有开始! As the nc client side is called right after the nc listening, there will be chance of the nc client start faster than the listening process, so I try to sleep sometime (~1s) after the nc -l command to make sure the listening process is started before the client start, then everything works fine now. 由于在nc侦听后立即调用nc客户端,因此nc客户端的启动速度可能比侦听过程快,因此我尝试在nc -l命令之后的某个时间(〜1s)进入睡眠状态,以确保侦听过程是在客户端启动之前启动的,那么现在一切正常。

Thanks all for the reply! 谢谢大家的答复!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM