Python Fabric - 删除我应该复制到远程文件的远程文件

时间:2015-06-10 18:28:42

标签: python file-upload file-io fabric remote-server

解决

看起来我需要用

关闭sys.stdout文件(可以写入)
sys.stdout.close()

然后重新打开它,但在读取模式下,用

sys.stdout = open ('/home/myuser/verify_yslog_conf/remote_hostname/hi', 'r')

然后正确上传。我用过

time.sleep(60)

在中途运行文件以进行故障排除。在def完成之前它是空的,默认情况下关闭“hi”文件。所以我意识到我需要关闭它以完全写入文件。谢谢。

下面的代码用于检查syslog是否正在运行,如果是,则从拉出的远程syslog.conf文件中注释掉带有“@”(但不是@ 192.168.x.xx或192.168.x.xxx)的任何行。在本地评论这些行之后,应该将新文件上载到旧位置的远程服务器。但是,所有发生的事情都是我的/etc/syslog.conf文件被删除了。该文件未被删除,它只是空的。

我知道问题来自put声明

fabric.operations.put('/home/myuser/verify_yslog_conf/remote_hostname/hi', '/etc/syslog.conf', use_sudo=True) 

但没有任何错误。

def verify():

#lines below are good; keep them

ip1 = '192.168.x.xx'
ip2 = '92.168.x.xxx'

#check if syslog is running

output = sudo("/sbin/service syslog status")
if 'is running...' in output:

    #pull the syslog file from the remote server

    fabric.operations.get('/etc/syslog.conf')

    #read thru the file 

    fh = open('/home/myuser/verify_yslog_conf/remote_hostname/syslog.conf', 'r')
    f = fh.read()
    fh.close()

    #if the file needs commenting ... 

    if re.search(r'(@(?!({0}|{1})))'.format(ip1, ip2), f):

        #get the file again -- maybe the problem? was advised to do this

        fabric.operations.get('/etc/syslog.conf')

        #save the file locally for reading and then for writing (r+ failed)

        conf = open ('/home/myuser/verify_yslog_conf/remote_hostname/syslog.conf', 'r')
        sys.stdout = open ('/home/myuser/verify_yslog_conf/remote_hostname/hi', 'w')

        #for every line in the old /etc/syslog.conf

        for line in conf:

            #if it has an @ but not followed by the permitted IPs

            if re.search(r'(@(?!({0}|{1})))'.format(ip1, ip2), line):

                #comment out the line then print it (does it twice, dont care)

                line = "#" + line
                sys.stdout.write(line) 
            sys.stdout.write(line)    
        conf.close()    

        #upload the newly commented file to the remote host

        fabric.operations.put('/home/myuser/verify_yslog_conf/remote_hostname/hi', '/etc/syslog.conf', use_sudo=True)    

    else:
        print GOOD
else:
    print RSYSLOG

1 个答案:

答案 0 :(得分:0)

module.exports.yeah.hallo.shine命令之前尝试sys.stdout.close()

可能在put操作之前,数据没有刷新到文件,因此它发送一个空文件,但是当脚本完成时,它会自动刷新(写入)数据,这就是文件显示正常的原因。本地系统。